简体   繁体   English

奇怪的PHP语法错误

[英]Strange PHP Syntax Error

I get the error You have an error in your SQL syntax; 我收到错误消息您的SQL语法错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'keys LIKE %dogs% ORDER BY rating DESC' at line 1 检查与您的MySQL服务器版本对应的手册以获取正确的语法,以在第1行的“ keys LIKE%dogs%ORDER BY rating DESC”附近使用

 $query = mysql_query("SELECT * FROM listings WHERE keys LIKE %$q% ORDER BY rating DESC") or die(mysql_error());

I searched for "dogs" which replaced the "q" search variable. 我搜索了替换“ q”搜索变量的“ dogs”。 This syntax error occured when I added the ORDER BY rating DESC. 当我添加ORDER BY等级DESC时,发生此语法错误。 I have the same line of code, minus that last past, and it works fine. 我有相同的代码行,减去了过去的代码,它工作正常。 I have tried adding single quotes around 'listings' 'keys' and 'rating' and it still did not work. 我尝试在“列表”,“键”和“评分”周围添加单引号,但仍然无法正常工作。

I'm sure this is an easy fix that I am just missing. 我确定这是一个简单的解决方法,我只是想念它。

Thanks 谢谢

It's not php error. 不是php错误。 String after LIKE should be quoted. LIKE之后的字符串应加引号。

Just a small comment, but related to the question: avoid using the classic MySQL extension. 只是一个小小的评论,但涉及到一个问题:避免使用经典的MySQL扩展。 Use the MySQL Improved version or, preferably, PDO. 使用MySQL改进版本,或者最好使用PDO。

http://php.net/manual/en/book.pdo.php http://php.net/manual/zh/book.pdo.php

http://php.net/manual/en/book.mysqli.php http://php.net/manual/zh/book.mysqli.php

Not only it's more secure, you'll be able to use MySQL 5 features such as prepared statements. 不仅更安全,而且您将能够使用MySQL 5功能(例如,准备好的语句)。

"keys" might be a reserved keyword. “键”可能是保留关键字。 Surround it with backticks. 用反引号将其包围。

Also, like @OZ_ said, the string after LIKE must be surrounded with single quotes. 另外,就像@OZ_所说的那样, LIKE之后的字符串必须用单引号引起来。 And escape $q to avoid SQL injection. 并转义$q以避免SQL注入。

$query = mysql_query("SELECT * FROM listings WHERE `keys` LIKE '%" . mysql_real_escape_string($q) . "%' ORDER BY rating DESC") or die(mysql_error());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM