简体   繁体   中英

Strange PHP Syntax Error

I get the 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 'keys LIKE %dogs% ORDER BY rating DESC' at line 1

 $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. This syntax error occured when I added the ORDER BY rating 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. String after LIKE should be quoted.

Just a small comment, but related to the question: avoid using the classic MySQL extension. Use the MySQL Improved version or, preferably, PDO.

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

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

Not only it's more secure, you'll be able to use MySQL 5 features such as prepared statements.

"keys" might be a reserved keyword. Surround it with backticks.

Also, like @OZ_ said, the string after LIKE must be surrounded with single quotes. And escape $q to avoid SQL injection.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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