views:

56

answers:

5

Hi all, So I have a primary key column called key. I'm trying to select the row with key = 1 via this code:

$query ="SELECT * FROM Bowlers WHERE key = '1'"; 
$result = mysql_query($query) or die(mysql_error());

For some reason, I'm getting this result:

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 = '1'' at line 1

The mysql statement works for using other keys, ie WHERE name = 'djs22'.

Any ideas?

+7  A: 

key is a reserved word, try putting ticks around it:

$query ="SELECT * FROM `Bowlers` WHERE `key` = '1'"; 
$result = mysql_query($query) or die(mysql_error());

To see all the reserved words, go here and scroll down: http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html

Kerry
+1 for the link
Unreason
Thanks! But now my next line: $row = mysql_fetch_assoc($result);is unhappy. Again, it works fine when not using the primary key.
djs22
What's the error?
Kerry
Isn't giving one,but it's choosing to go the or die route every time...
djs22
There's no MySQL or PHP error?
Kerry
+2  A: 

'key' is a reserved keyword, put backtick quotes around it:

"SELECT * FROM Bowlers WHERE `key` = '1'"
mercutio
...and if `key` is a numeric type, then the literal should NOT have quotes (it'll work - but it'll go much slower)
symcbean
@symcbean OMG "much slower". You have no idea of slowness
Col. Shrapnel
Indeed, it will be optimised away easily, especially as it's the primary key. The difference in timings is negligible. However, I do agree that putting quotes around numeric literals is bad style.
mercutio
+2  A: 

Without checking, it's likely that "key" is a reserved word in MySQL. Try wrapping it in backticks

$query ="SELECT * FROM Bowlers WHERE `key` = '1'";  
Mark Baker
+1  A: 

You should write the column name key in quotes

$query ="SELECT * FROM Bowlers WHERE `key` = '1'";

Otherwise it is a keyword

Unreason
A: 
Cory Cullers