mysql语法错误(在select查询中)报告错误[关闭]

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

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?

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");

to is reserved keyword use quote identifier to escape it.

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