[英]How can I select data from table based on one or multiple condition?
I am working using MySQL/PHP, I wanted to select data from a table based on one or more condition but using minimum if statements. 我正在使用MySQL / PHP,我想基于一个或多个条件但使用最少的if语句从表中选择数据。 For example if I have a table
例如,如果我有一张桌子
Students | Register | End | Points
Mark | 14/1 | 18/6 | 14
Dina | 18/12 | 19/2 | 1
Karl | 1/1 | 1/2 | 9
I have a form where user can look for data based on one or more criteria (register, end, points) based on the data he chose to set. 我有一个表格,用户可以根据他选择设置的数据基于一个或多个条件(寄存器,终点,点)来查找数据。
If he only set one of the criteria lets say after an date, he will get all results based on that date. 如果他只设置了一个条件,可以说在一个日期之后说,那么他将基于该日期获得所有结果。
If he set two or three conditions maybe (register and end) or (end and points) or even (register and end and points) he will get the result based on all conditions joint together not only one of them or all of them separately. 如果他设置两个或三个条件(注册和结束),(结束和点)甚至(注册和结束和点),他将基于所有条件结合在一起获得结果,而不仅是其中一个条件,也可能是所有条件都分开。
when I use AND between conditions and the user don't set one of the conditions it returns empty query. 当我在条件之间使用AND且用户未设置条件之一时,它将返回空查询。
when I use OR between conditions and the user choose multiple conditions it returns data but based on each of conditions separately not joining it. 当我在条件之间使用OR且用户选择多个条件时,它返回数据,但基于每个条件分别不连接它。
Queries I tried: 我尝试过的查询:
SELECT * FROM table WHERE Register >= '$choice1' OR End <= '$choice2' OR Points = '$choice3';
SELECT * FROM table WHERE Register >= '$choice1' AND End <= '$choice2' AND Points = '$choice3';
What is the best way to do that? 最好的方法是什么?
Use php to build your WHERE
clause, something like this: 使用php构建您的
WHERE
子句,如下所示:
$condition = '';
if($choice1 != '')
$condition .= "Register >= '$choice1'";
if($choice2 != '')
$condition .= ($condition != '' ? " AND " : '') . "End <= '$choice2'";
if($choice3 != '')
$condition .= ($condition != '' ? " AND " : '') . "Points = '$choice3'";
$sql = "SELECT * FROM table" .($condition != '' ? " WHERE $condition;" : ";");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.