mysql语法错误(在选择查询中)报告错误

时间:2013-06-16 14:25:39

标签: php mysql

下面的PHP代码报告错误代码:

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

报告的错误是:

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'表示$ _SESSION ['sno']设置为1

3 个答案:

答案 0 :(得分:2)

这是因为您使用的是mysql reserved keyword

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

TO是一个保留关键字,用反引号括起来以避免错误

由于不建议使用{n mysql_*一面,最好切换到PDOmysqli并使用预备语句以避免mysql injections的任何风险,请在此处了解详情{ {3}}

答案 1 :(得分:2)

to是保留关键字使用引号标识符来逃避它。

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

答案 2 :(得分:0)

你必须使用`sign来表示喜欢的单词,因为这是My SQL的关键字。

所以你的查询看起来像是

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