-1
$NumPMs = mysql_query("SELECT * FROM messages WHERE to_user='$name' AND read='0'") or die (mysql_error());
$numofpms = mysql_num_rows($NumPMS);

I get this 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 'read='0'' at line 1

It doesn't make sense. It should be working.

Help would be appreciated!

EDIT:

I changed the query to this: $NumPMs = mysql_query("SELECT * FROM messages WHERE to_user='$name' AND read='0'") or die (mysql_error());

It works. Although, my mysql_num_rows flares an error too: Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /home/recatio2/public_html/Main.php on line 78

Please help.

4

4 回答 4

2

read是 MySQL 中的保留关键字。您可以使用反引号转义所有字段名称:

$NumPMs = mysql_query("SELECT * FROM messages WHERE `to_user`='$name' AND `read`='0'") or die (mysql_error());
于 2013-06-27T13:53:54.640 回答
2

您应该在将字段名称和 $n​​ame 添加到 SQL 之前对其进行转义。

$NumPMs = mysql_query("SELECT * FROM `messages` WHERE `to_user`='". mysql_real_escape_string($name)."' AND `read`='0'") or die (mysql_error());
于 2013-06-27T13:53:41.343 回答
1

READ 是一个 mysql_reserved 字;您可以在以下位置查看列表: http ://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

一种解决方案是用反引号来逃避它:

SELECT * FROM messages WHERE to_user='$name' AND `read`='0'

另一种是将字段重命名为其他名称 - 将保留字用于列名或表名不是一个好习惯。

于 2013-06-27T13:55:08.757 回答
0
$NumPMs = mysql_query("SELECT * FROM messages m WHERE m.to_user='$name' AND m.read='0'")

为表使用别名以避免与保留的 MySQL 关键字冲突。

使用别名明确地明确哪些列是从哪个表引用的也是一个好主意。一旦您的查询变得更加复杂并涉及更多表,您就会看到这样做的好处。

于 2013-06-27T13:56:29.587 回答