Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

php

mysql

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.

like image 713
mayur bhagat Avatar asked Jan 27 '26 04:01

mayur bhagat


2 Answers

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
  • SQLFiddle Demo

OTHER SOURCE(s)

  • MySQL Reserved Keywords List

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.

  • How to prevent SQL injection in PHP?
like image 122
John Woo Avatar answered Jan 29 '26 20:01

John Woo


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

like image 34
Gung Foo Avatar answered Jan 29 '26 20:01

Gung Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!