Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I am trying to insert data in a database table named "contact_info" but I am facing this while inserting the data.

This is the Error

<pre>You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'add,phn1,phn2,phn3,email1,email2)values('hh h h','987654320', '123456789' at line 1.


What I have tried:

<?php
$con=mysqli_connect("localhost","root","","uca");
//fetch data
$of_add=$_POST["office_add"];
$con_mob1=$_POST["con_mob1"];
$con_mob2=$_POST["con_mob2"];
$con_mob3=$_POST["con_mob3"];
$enm1=$_POST["enm1"];
$enm2=$_POST["enm2"];
//insertion query
$r=mysqli_query($con,"insert into contact_info(add,phn1,phn2,phn3,email1,email2)values('$of_add','$con_mob1',
'$con_mob2','$con_mob3','$enm1','$enm2')");

if($r){

	echo "done";
}
else{
	echo mysqli_error($con);
}
?>
Posted
Updated 1-Jul-21 0:50am

ADD is a reserved word. You need to quote it to use it as a column name:
SQL
insert into contact_info (`add`, phn1, ...
MySQL :: MySQL 8.0 Reference Manual :: 9.3 Keywords and Reserved Words[^]

But as Griff said, your code is vulnerable to SQL Injection[^]. NEVER use string concatenation/interpolation to build a SQL query. ALWAYS use a parameterized query.

PHP: SQL Injection - Manual[^]
 
Share this answer
 
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Fix that throughout your app, and the problem you have noticed will go at the same time ...
 
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