Could anyone suggest why the greater than operator is being ignored in this MySQL query?
$sql = "SELECT *
FROM `items`
WHERE `short_description` LIKE '%".$term."%'
OR `description` LIKE '%".$term."%'
AND `quantity` > 0
ORDER BY year DESC, denomination ASC, description ASC $max";
I have a similar query on the same site that works
$sql = "SELECT *
FROM `items`
WHERE `category` = '".$cat_id."'
AND `quantity` > 0
ORDER BY year DESC, denomination ASC, description ASC;";
Everything works well, except the quantity comparison on the first query, Its has got me stumped.
you should group your OR
and AND
conditions by enclosing them in a parenthesis,
$sql = "SELECT * FROM `items`
WHERE (`short_description` LIKE '%".$term."%' OR
`description` LIKE '%".$term."%') AND
`quantity` > 0
ORDER BY year DESC, denomination ASC, description ASC $max";
followup question: is $max
a variable which contains LIMIT
clause?
As a sidenote, the query is vulnerable with SQL Injection
if the value( s ) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements
you can get rid of using single quotes around values.
"SELECT * FROM items WHERE (short_description LIKE '%".$term."%' OR description LIKE
'%".$term."%')
AND quantity > 0
ORDER BY year DESC, denomination ASC, description ASC $max";
Try that... You have an Or condition, and an and.
Try
$sql = "SELECT *
FROM `items`
WHERE (`short_description` LIKE '%".$term."%'
OR `description` LIKE '%".$term."%')
AND `quantity` > 0
ORDER BY year DESC, denomination ASC, description ASC $max";
I am thinking that your OR
statement is the problem.
It's not being ignored, it's just that you misunderstand how it's being applied. The expression:
WHERE `short_description` LIKE '%".$term."%' (call this XX,)
OR `description` LIKE '%".$term."%' ( YY,)
AND `quantity` > 0 ( and ZZ.)
is interpreted as:
where XX or (YY and ZZ)
whereas what you probably want is:
where (XX or YY) and ZZ
Hence you have to override the default interpretation as follows:
WHERE (`short_description` LIKE '%".$term."%' OR
`description` LIKE '%".$term."%')
AND `quantity` > 0
The reason your second query doesn't have this problem is because you're not mixing AND
and OR
.
In addition, though unrelated to your specific question), you should be very wary of double-ended like
clauses such as like '%something%'
. They're real performance killers for decent sized tables and there are ways to improve the performance considerably.
It may not matter in this case if your tables are small but it's something to keep in mind.
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.