1

我有一些像这样的复选框

<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

4

1 回答 1

2
$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) . ')';
}
于 2013-01-20T12:37:15.047 回答