简体   繁体   中英

php/mysql search for multiple values

I have a table homes with (country,city,area,published) fields. I have a search form where someone can enter country or city or area. I want to get all homes which are published = 1 and any of the search terms matches any of their fields.

This is what I have so far:

SELECT * FROM homes 
WHERE published = 1 
AND 
LOWER(country) LIKE '$search%' 
OR 
LOWER(city) LIKE '$search%'
OR
LOWER(area) LIKE '$search%'

The problem is that it return homes that have published = 0...

I would suggest parentheses.

SELECT * FROM homes 
WHERE published = 1 
AND
(
 LOWER(country) LIKE '$search%' 
 OR 
 LOWER(city) LIKE '$search%'
 OR
 LOWER(area) LIKE '$search%'
)
SELECT * 
FROM   homes 
WHERE  published = 1 
       AND ( country LIKE '$search%' 
              OR city LIKE '$search%' 
              OR area LIKE '$search%' ) 

Like already does the case-insensitive stuff so you don't need it.

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

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