mayur bhagat
mayur bhagat

Reputation: 209

Getting syntax error in mysql-php. You have an error in your SQL syntax;

I am using table user_like to save user like hits.

Table structure is as follow.

id  user_id     song_id     like
--------------------------------
67    2           148         0

All column datatype is int(11).

$song_id=$_GET['song_id'];
$query="select * from atr_like WHERE song_id = '$song_id' and like = 0";
$rs = mysql_query($query) or
die(mysql_error());
echo mysql_num_rows($rs);

I am getting following 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 'like = 0' at line 1.

I am not able to point out root cause of error is it looks everthing is okay.

Please help.

Thanks in advance.

Upvotes: 2

Views: 196

Answers (2)

John Woo
John Woo

Reputation: 263723

LIKE is a reserved keyword. You can escape it with backtick.

SELECT  * 
FROM    atr_like 
WHERE   song_id = '$song_id' and 
        `like` = 0

Another way is to supply alias on the table, eg

SELECT  a.* 
FROM    atr_like a
WHERE   a.song_id = '$song_id' and 
        a.like = 0

OTHER SOURCE(s)

If you have time to alter it, don't use tablename or columnname which is on the reserved keyword list. it will give you such pain in the neck on the future.

As a sidenote, the query is vulnerable with SQL Injection if the value(s) came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Upvotes: 10

Gung Foo
Gung Foo

Reputation: 13558

LIKE is a reserved keyword. Don't name your colums after such.

http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

Upvotes: 1

Related Questions