【问题标题】:How to add values from checkboxes to 'select' query?如何将复选框中的值添加到“选择”查询?
【发布时间】:2013-01-03 16:12:32
【问题描述】:

我有一些这样的复选框

<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

【问题讨论】:

标签: php sql post checkbox


【解决方案1】:
$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) . ')';
}

【讨论】:

  • demo: kraleksandr.dlinkddns.com/tt.php(可能不可用)如果我检查了 0 和 1,$sql 是 SELECT name,lvl,team FROM table WHERE AND lvl IN (0,1)
  • 你在使用我所有的代码吗?试试array_search('0', $vals) 而不是array_search(0, $vals)
  • 您显然没有在 tt.php 上实现我的代码,因为当我选择“0”选项时,WHERE 语句的构造不正确。 '0' 值在数组中有一个键 '0' 和一个值 '0'。
  • 你能给我一个建议,我现在必须改变什么吗?
  • 当你var_dump($vals)在提交表单并选择了'0'后会发生什么?
猜你喜欢
  • 2021-01-07
  • 2014-07-07
  • 1970-01-01
  • 2015-08-17
  • 2019-02-28
  • 2011-11-16
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
相关资源
最近更新 更多