0

PHP code below reports an error code:

$id = $_SESSION['sno'];
$q = mysql_query("select * from messages where seen=0 and to=$id");
if(!$q){die("critical failure: ".mysql_error());}

Error reported is:

critical failure: 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 'to=1' at line 1

'to=1' shows that $_SESSION['sno'] is set to 1

gcbenison
  • 11,723
  • 4
  • 44
  • 82
  • You should use MySQLi or PDO instead of `mysql_*` functions, which are deprecated. [More information avalible here](http://cz2.php.net/manual/en/mysqlinfo.api.choosing.php). – Petr R. Jun 16 '13 at 14:29

3 Answers3

2

This is because you are using a mysql reserved keyword

$q = mysql_query("select * from messages where seen=0 and `to`=$id");

TO is a reserved keyword, surround it with backticks ` to avoid the error

As side nmysql_* finction are deprecated, better to switch either to PDO or mysqli and use prepared statements to avoid any risk of mysql injections, learn more here How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Fabio
  • 23,183
  • 12
  • 55
  • 64
2

to is reserved keyword use quote identifier to escape it.

mysql_query("select * from messages where `seen`=0 and `to`=$id"); 
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
0

You have to use ` sign for words like to as this is keywords of My SQL.

So your query looks like

$q = mysql_query("select * from messages where seen=0 and `to`=$id");
ankit shah
  • 54
  • 1
  • 8