如何从复选框添加值到'select'查询


How to add values from checkboxes to 'select' query?

我有一些像这样的复选框

<form action="tt.php" method="post">
<input type="checkbox" name="lvl[]" value="0">0&nbsp
<input type="checkbox" name="lvl[]" value="1">1&nbsp
<input type="checkbox" name="lvl[]" value="2">2&nbsp
<input type="checkbox" name="lvl[]" value="3">3&nbsp
<input type="checkbox" name="lvl[]" value="4">4&nbsp
<input type="submit" value="Ok">

如何从检查的值添加到这样的SQL查询?:

如果选中2和4,则
select name,lvl,team from $table where lvl=2 or lvl=4
如果选中2和4 and 0
select name,lvl,team from $table where lvl=2 or lvl=4 or team='abc'(如果选中0则'select'必须包含team='abc'的字符串,如果不选中-不选中)
如果不选择,则
select name,lvl,team from $table

$where = '';
if (isset($_POST['lvl']) && $vals = $_POST['lvl']) {
   // Begin WHERE string
   $where = 'WHERE '; 
   // Remove '0' from array
   if ($key = array_search('0', $vals)) {
      $where .= 'team = "abc" ';
      unset($vals[$key]);
   } 
   // Append `WHERE lvl IN (2,4)`
   $where .= 'AND lvl IN (' . implode(',', $vals) . ')';
   // Final statement
}
$sql = "select name,lvl,team from $table $where";

编辑

如果你替换这个会发生什么:

if ($key = array_search('0', $vals)) {
   $where .= 'team = "abc" ';
   unset($vals[$key]);
} 

:

if ($vals[0] === '0') {
   $where .= 'team = "abc" ';
   unset($vals[0]);
} 

把你的代码改成:

$first = false;
if ($vals[0] === '0') {
    $where .= 'team = "neutral"';
    unset($vals[0]);
    $first = true;
}
if (count($vals)) {
    if ($first) $where .= ' OR ';
    $where .= 'lvl IN (' . implode(',', $vals) . ')';
}