简体   繁体   中英

Multiple Search Filters MySQL Database

I have a database containing information about a person. Lets say I want to search people from a country. So I type in USA and got 10 data. After that, I would want to further narrow down to people who are male.

How do I do a SQL that can first search for country, then search for gender.

$sql="SELECT * FROM people 
  WHERE country like $search1%
  ORDER BY ASC ";

And

$sql="SELECT * FROM people 
  WHERE country like $search1%
  AND Gender = $search2
  ORDER BY ASC ";

How do I combine them into one $sql statement?

Try to combine all cases with this code:

$sql = "SELECT *
FROM people
WHERE (country LIKE %$search1% AND $search2='')
OR ($search1='' AND gender=$search2)
OR (country LIKE %$search1% AND gender=$search2)";

Add your own ORDER BY clause.

Updated

SELECT * 
FROM people 
WHERE 
((country = ('USA') AND gender = 'male') 
OR 
(country LIKE ('USA') OR gender LIKE 'male'))
ORDER BY ASC

First line ((country = ('USA') AND gender = 'male')

For both Second line (country LIKE ('USA') OR gender LIKE 'male'))

For either put '%' in the one you don't need.

For example (country LIKE ('USA') OR gender LIKE '%'))

Sub query:

SELECT * FROM (SELECT * FROM people WHERE country like $search1% ) as people1 WHERE Gender = $search2 ORDER BY ASC

you can combine this. first check the filter has a value or not.

to check using if condition and concate a string and then execute it, like a.

$sql="SELECT * FROM people WHERE 1 ";
if($search1% != NULL){
   $sql.="AND country like $search1% ";
}
elseif($search2 != NULL){
   $sql.="AND Gender = $search2 ";
}
$sql.="ORDER BY ASC ";

There are two ways

  1. Create view in MySql For such complex query

  2. write a function in php to build query for above

      <?php function searchQuery($key,$gender,$order){ $sql = "SELECT * FROM people WHERE country like %$key% AND Gender = $gender ORDER BY $order" $query= mysql_query($sql); while($data= mysql_fetch_array($query)) { //Do your stuff here and collect in one variable say $searchData } return $searchData } 

Hope this will help you

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