Question

I have got following error in a simple PHP page when I tried to insert a row in a table "userstbl"

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'userstbl\' (\'usr_name\', \'usr_pwd\', \'usr_fname\', \'usr_lname\') VALUES (\' at line 1

Here is the code:

$con = mysqli_connect("localhost","root","","test_sms"); 
if (mysqli_connect_errno())
{
    echo "Failed to connect:" . mysqli_connect_error();
    }
$value = "INSERT INTO 'userstbl' ('usr_name', 'usr_pwd', 'usr_fname', 'usr_lname') VALUES ('Aftab','xyz','Aftab','Hussain')";
$sqlin = mysql_prep($value);
if (!mysqli_query($con, $sqlin)){
    die ('Error: ' . mysqli_error($con));
    }
$sqlot = "SELECT * FROM 'usertbl'";
$sqlo = mysql_prep($sqlot);
$sqlout = mysqli_query($con , $sqlo);
echo "<table border='1'><tr><th>ID</th><th>Username</th><th>Password</th><th>First Name</th><th>Last Name</th></tr>";
while ($row = mysqli_fetch_array($sqlout));
{
    echo "<tr>";
    echo "<td>" . $row['usr_id'] . "</td>";
    echo "<td>" . $row['usr_name'] . "</td>";
    echo "<td>" . $row['usr_pwd'] . "</td>";
    echo "<td>" . $row['usr_fname'] . "</td>";
    echo "<td>" . $row['usr_lname'] . "</td>";
    echo "</tr>";
    }

mysqli_close($con);
?>
Was it helpful?

Solution 2

try

$con = mysqli_connect("localhost","root","","test_sms"); 
if (mysqli_connect_errno())
{
    echo "Failed to connect:" . mysqli_connect_error();
    }
$value = "INSERT INTO userstbl (usr_name, usr_pwd, usr_fname, usr_lname) VALUES ('Aftab','xyz','Aftab','Hussain')";
$sqlin = mysql_prep($value);
if (!mysqli_query($con, $sqlin)){
    die ('Error: ' . mysqli_error($con));
    }
$sqlot = "SELECT * FROM usertbl";
$sqlo = mysql_prep($sqlot);
$sqlout = mysqli_query($con , $sqlo);
echo "<table border='1'><tr><th>ID</th><th>Username</th><th>Password</th><th>First Name</th><th>Last Name</th></tr>";
while ($row = mysqli_fetch_array($sqlout));
{
    echo "<tr>";
    echo "<td>" . $row['usr_id'] . "</td>";
    echo "<td>" . $row['usr_name'] . "</td>";
    echo "<td>" . $row['usr_pwd'] . "</td>";
    echo "<td>" . $row['usr_fname'] . "</td>";
    echo "<td>" . $row['usr_lname'] . "</td>";
    echo "</tr>";
    }

mysqli_close($con);
?>

OTHER TIPS

If you want to escape column and table names use backticks, not quotes

INSERT INTO `userstbl` (`usr_name`, usr_pwd, usr_fname, usr_lname)
VALUES ('Aftab', 'xyz', 'Aftab', 'Hussain')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top