如何将多个Checkbox查询更改为多个选择的jQuery?

时间:2015-08-18 21:40:21

标签: php jquery mysql jquery-chosen

我有一个多重复选框查询,如下所示

  <span style="width:276px;display:inline-block;">&nbsp;<input type="checkbox" name="check_list[]" value="sub_category_id = '1''">Name1</span>

  <span style="width:276px;display:inline-block;">&nbsp;<input type="checkbox" name="check_list[]" value="sub_category_id = '2'">Name2</span>

  <span style="width:276px;display:inline-block;">&nbsp;<input type="checkbox" name="check_list[]" value="sub_category_id = '3'">Name3</span>

  <span style="width:276px;display:inline-block;">&nbsp;<input type="checkbox" name="check_list[]" value="sub_category_id = '4'">Name4</span>

然后

 <?php
 $names = implode(' or ', (array)$_POST['check_list'.$i]);
 echo $names;
 ?>

我收到了部分问题。

sub_category_id = '1'' or sub_category_id = '2' or sub_category_id = '3' or sub_category_id = '4'

使用选择的Jquery,我能够检索MySQL数据(Name1,Name2,Name3,Name4),如下所示:

   <select name="sub_category_id[]" id="sub_category_id[]" multiple     class="chosen-select" tabindex="8">
   <option value="">Selecione...</option>
    <?php foreach ($arrEstados as $value => $name) {
      echo "<option value='{$value}'>{$name}</option>";
    }?>
  </select>

  $names = $_POST['sub_category_id'];
  $query=implode('sub_category_id=', $names);
  echo $query;

但是'或'缺失了。我没有很好的PHP技能,所以我问:这是获取查询的正确方法吗?我没有使用PDO或mysqli。

2 个答案:

答案 0 :(得分:0)

更改你的html select元素,然后按照:

<select name="check_list[sub_category_id][]" id="sub_category_id[]" multiple     class="chosen-select" tabindex="8">
    <option value="">Selecione...</option>
    <?php
        foreach ($arrEstados as $value => $name) {
            echo "<option value='{$value}'>{$name}</option>";
        }
    ?>
</select>

这样做会在你的$ _POST:

中创建一个这样的数组
$_POST => Array
    (
        [check_list] => Array
            (
                [sub_category_id] => Array
                    (
                        [0] => 2
                        [1] => 3
                    )

            )

    )

然后改变你的PHP:

<?php
        $names = isset($_POST['check_list']) && isset($_POST['check_list']['sub_category_id']) ? $_POST['check_list']['sub_category_id'] : NULL;
        $query = "SELECT * FROM tablename WHERE ";
        if(!is_null($names)){
            foreach($names as $i => $name){
                if($i !== 0){
                    $query .= " OR ";
                }
                $query .= "sub_category_id = '$name'";
            }
        }
        echo($query);
        //Output: SELECT * FROM tablename WHERE sub_category_id = '2' OR sub_category_id = '3'   
    }
?>

您可能需要更改查询以适合您的应用程序,但这将有助于您朝着正确的方向前进。

答案 1 :(得分:0)

正如马丁所说,de http://www.tutorialspoint.com/mysql/mysql-in-clause.htm转变了解决问题的简单方法。这就是我所做的:

 <select chosen still the same...>

 $sub_category_1 = $_POST['sub_category_id'];
 $query=implode(',', $sub_category_1);

 $sql = "Select * from table WHERE sub_category_id IN($query)";