我有5个复选框变量。
为了避免在取消选中复选框时出现“未定义索引”的问题,我使用了这个:
<input value="" name="checkbox1">
<input value="C1" name="checkbox1">
<input value="" name="checkbox2">
<input value="C2" name="checkbox2">
<input value="" name="checkbox3">
<input value="C3" name="checkbox3">
<input value="" name="checkbox4">
<input value="C4" name="checkbox4">
<input value="" name="checkbox5">
<input value="C5" name="checkbox5">
$col1 = $_POST['checkbox1'];
$col2 = $_POST['checkbox2'];
$col3 = $_POST['checkbox3'];
$col4 = $_POST['checkbox4'];
$col5 = $_POST['checkbox5'];
现在,我想写一个这样的查询:
$query = "Select * from users where 1=1 ";
if($_POST['checkbox1'] !=="") {
$query.="And/OR col1='$col1'";
}
if($_POST['checkbox2'] !=="") {
$query.="And/OR col2='$col2'";
}
if($_POST['checkbox3'] !=="") {
$query.="And/OR col3='$col3'";
}
if($_POST['checkbox4'] !=="") {
$query.="And/OR col4='$col4'";
}
if($_POST['checkbox5'] !=="") {
$query.="And/OR col5='$col5'";
}
问题在于“和/或”。
如果发生第一个复选框被选中,那么它应该是“And”,如果它是第二个从那些选中的复选框然后“或”。任何想法是如何执行此操作?
例如:如果第一个选择了$ col2复选框,并且用户也选择了$ col4复选框,则$ query应为:
"Select * users where 1=1 AND col2=$col2 OR col4=$col4"
答案 0 :(得分:0)
你可以这样做:
$query = "Select * from users where 1=1 ";
$chosen = false;
if($_POST['checkbox1'] !=="") {
$query.="And col1='$col1'";
$chosen = true;
}
if($_POST['checkbox2'] !=="") {
$query.= (($chosen) ? "OR" : "And") . " col2='$col2'";
$chosen = true;
}
if($_POST['checkbox3'] !=="") {
$query.= (($chosen) ? "OR" : "And") . " col3='$col3'";
$chosen = true;
}
...........................
答案 1 :(得分:0)
试试这个:
$query = "Select * from users where 1=1 ";
$where = "";
$where_arr = array();
if($_POST['checkbox1'] !=="") {
$where_arr[]=" col1='$col1'";
}
if($_POST['checkbox2'] !=="") {
$where_arr[]=" col2='$col2'";
}
if($_POST['checkbox3'] !=="") {
$where_arr[]=" col3='$col3'";
}
if($_POST['checkbox4'] !=="") {
$where_arr[]=" col4='$col4'";
}
if($_POST['checkbox5'] !=="") {
$where_arr[]=" col5='$col5'";
}
if(count($where_arr))
$where = " AND ".implode(" OR ", $where_arr);
$query .= $where;