如何将复选框中的值添加到“选择”查询?

时间:2013-01-20 12:29:19

标签: php sql post checkbox

我有一些像这样的复选框

<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

1 个答案:

答案 0 :(得分: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) . ')';
}