简体   繁体   中英

PHP and SQL multiple/conditional filters query

I have a table with the following fields

id | Name         | Gender | Country | Math | English | Science
---------------------------------------------------------------
1  | Paul Allen   | Male   | USA     | 4    | 2       | 
2  | Andrew Cur   | Male   | GBR     |      | 1       | 2
3  | Paul Hanz    | Male   | GER     | 5    | 2       | 2
4  | Angela Dow   | Female | AUT     | 3    |         | 1
5  | Dana Loconto | Female | USA     | 2    |         |

My users are allowed to filter this table in many ways, using a html form and php. They can filter by username, filter by country, filter by gender. That is pretty simple to acomplish. My problem is, that I need to be able to filter also depending on the grade. For example:

"I want to know all females that have Math grade of 2 AND 3, and also have Science grade of 1".

Even though I know how to write a query by hand using ANDs and ORs, it's proving to be hard for me to organize the final query depending on the parameters that my users pass using the form. Specially when it comes to the grades.

Any insights to direct me to the right path?

EDIT: After a few suggestions, I also used the following:

 'code' $cchair = count($_POST['f_chair']);
$commas = 1; 
$query_officials .= " AND o_math IN (";
foreach($_POST['f_math'] as $val) { 
$query_officials .= "'".$val."'"; 
if ($commas < $cchair) { $query_officials .= ", "; $commas++; } 
}
$query_officials .= ")";

Something like this below should work. Note that you'd need to allow for multiple selection of some values (for example, you can select more than one grade in a dropdownlist), so you build your query like that. I have not tested this piece exactly but used this approach before and it works.

$query = “select * from mytable where ” 
If(isset($_POST['gender']) {  //First field
    $query .=  "gender = " . $_POST['gender']
}

If(isset($_POST['math']) {  //Second field (array type of field since there could be more than one choice in the drop down)
    $query .=  "AND math in ( ";
    foreach($_POST['math'] as $value)
        {
            $query .= $value . ','
        }
    $query .= ')';
}
//You repeat this for every field that has a value from your form

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