简体   繁体   中英

Having MYSQL Syntax error in PHP when using multiple AND

I have this SQL code

$sql = 'SELECT * FROM images WHERE 
(artist LIKE "'.$artistsearch.'%") 
AND (code LIKE "'.$idsearch.'%") 
AND (name LIKE "'.$namesearch.'%") 
AND (price BETWEEN '.$minprice.' AND '.$maxprice.')';

And I get the error

Invalid query: 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 'AND )' at line 5

However, running the code

SELECT * 
FROM images WHERE artist LIKE '%' 
AND code LIKE '%' 
AND name LIKE '%' 
AND price BETWEEN 0 AND 1000

Works fine in MySQL.

I've tried switching around ' and " and it doesn't work.

Can anyone help me figure out the problem?

The error says the everything the problem in the last line

AND (price BETWEEN '.$minprice.' AND '.$maxprice.')';

as you can see "AND $maxprice )" part is the problem. Check the $maxprice and be sure it is not empty

if (empty($maxprice)) {
   $maxprice = "some_default_number";
}

$sql = 'SELECT * FROM images WHERE 
   (artist LIKE "'.$artistsearch.'%") 
   AND (code LIKE "'.$idsearch.'%") 
   AND (name LIKE "'.$namesearch.'%") 
   AND (price BETWEEN '.$minprice.' AND '.$maxprice.')';

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