Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am self learning php/Mysql. I wrote the following code

$con=mysqli_connect("localhost","mangala","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO groups(Desc) VALUES('$_POST[desc]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

When I call this php file in HTML, shows following error

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 'Desc) VALUES('Desktop')' at line 1

anyone can help me?
Posted

1 solution

It seems that it is an issue with reserved words in MySQL engine. You should use double quotes or backtick/backquotes with these words. For example:
SQL
$sql="INSERT INTO groups(`Desc`) VALUES('$_POST[desc]')";

Please refer to MySQL 5.7 Reference Manual 9.3 Reserved Words[^] for more details.
Also consider to use parameters instead of using a $_POST or $_GET variables. For example:
PHP
$statement = $db->prepare("INSERT INTO groups(`Desc`) VALUES(:desc_column)");
$statement->execute(array('desc_column' => $_POST[desc]));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900