简体   繁体   中英

PHP with MySQL query not returning expected results

I'm new to PHP and I'm trying to select records (for search functionality) in my table where the month is static and other columns vary.

Below is the query:

SELECT * 
FROM issue 
WHERE month = "Apr 2019" 
    AND issue LIKE "%ekh%" 
    OR issue_type LIKE "%ekh%" 
    OR facility LIKE "%ekh%" 
    OR issue_id LIKE "%ekh%" 
    OR priority LIKE "%ekh%" 
ORDER BY issue_id DESC

This is rather returning all rows that satisfy the like clauses, even when month isnt = "Apr 2019".

In algebra, the AND operation is done before the OR operation. This is the same rule in your WHERE clause.

You can fix this with parentheses like this :

SELECT *
FROM issue
WHERE month = "Apr 2019"
    AND (issue LIKE "%ekh%"
        OR issue_type LIKE "%ekh%"
        OR facility LIKE "%ekh%"
        OR issue_id LIKE "%ekh%"
        OR priority LIKE "%ekh%")
ORDER BY issue_id DESC

When mysql hits first or it automatically returns everything because or something is true . Therefore you should use parentheses:

SELECT *
FROM issue
WHERE month = "Apr 2019" AND
(issue like "%ekh%" OR
 issue_type like "%ekh%" OR
 facility like "%ekh%" OR
 issue_id like "%ekh%" OR
 priority like "%ekh%")
ORDER BY issue_id DESC

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