简体   繁体   English

PHP和SQL多重/条件过滤器查询

[英]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. 我的用户可以使用html表单和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". “我想知道所有数学等级为2和3,科学等级为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. 即使我知道如何使用AND和OR编写查询,事实证明我还是很难根据用户使用表单传递的参数来组织最终查询。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM