-2

I am new user in php. I am trying insert in a table using following query:

$insert = "INSERT INTO forget (key,user_name) values('Abc','Xyz')";
mysql_query($insert)
echo mysql_error();

Output:

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 'key,user_name) values('abc','xyz')' at line 1

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
  • please edit your question so that it is readable, with code-blocks, etc... – Jeff May 17 '15 at 11:55
  • learn to interpret error messages. MySQL was telling you `for the right syntax to use near 'key` - **near `'key`**. Plus, don't bother using the plural form, `keys` is a reserved word also. Stay away from using those as much as possible. – Funk Forty Niner May 17 '15 at 12:39

2 Answers2

1

MySQL has a few reserved words which will cause queries using them to fail. In this case it is key.

You can either change the column name (also known as "key" which is why it fails) or you can escape the term with backticks like so:

$insert = "INSERT INTO forget (`key`,user_name) values('Abc','Xyz')"; 
nomistic
  • 2,902
  • 4
  • 20
  • 36
  • 1. Are you sure you are using backticks and not single quotes? 2. If so, can you provide your table structure? There's something missing from the information you provided – nomistic May 17 '15 at 12:17
  • I have change the column name. Structure is index,recover,username int,varchar,varchar – sourbh lamba May 17 '15 at 12:21
0

Here are the list of words what mysql has reserved, and that cant be used as a table or field name in a query, unless its escaped using back ticks. You can use them as your field name, but when you query it, it must be escaped using " ` ".

In your case, key is a reserved word. So you must either escape it using back ticks.

Here is a list of mysql reserved words : https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

Kishor
  • 1,513
  • 2
  • 15
  • 25