使复选框选择要从数据库显示的内容

时间:2014-03-23 11:29:42

标签: php jquery mysql checkbox

我正在创建一个网站,用户应该检查几个复选框,然后该网站会在表格中显示数据。

我一直在看这个"guide",但无法让它在我的页面上运行。我的index.php没有结果,submit.php只显示“Array []”

这是我到目前为止所做的:

Index.php包含复选框和jQuery脚本。

复选框位于下拉菜单中,如下所示:

    <div id="menu">
      <div id="mainmenu"><a href="#" onclick="toggle('submenu1')">Gender</a></div>
      <div id="submenu1" style="display:none">
        <div id="submenu"><a href="#">
          <input type="checkbox" name="gender" value="male">Male</a></div>
        <div id="submenu"><a href="#">
          <input type="checkbox" name="gender" value="female">Female</a></div>
      </div>
      <div id="mainmenu"><a href="#" onclick="toggle('submenu2')">Price range</a></div>
      <div id="submenu2" style="display:none">
        <div id="submenu"><a href="#">
          <input type="checkbox" name="price_range" value="200">200-299$</a></div>
        <div id="submenu"><a href="#">
          <input type="checkbox" name="price_range" value="300">300-399$</a></div>
        <div id="submenu"><a href="#">
          <input type="checkbox" name="price_range" value="400">400-499$</a></div>
      </div>

jQuery脚本:

<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script>
      function makeTable(data){
        console.log(data);
       var tbl_body = "";
          $.each(data, function() {
            var tbl_row = "";
            $.each(this, function(k , v) {
              tbl_row += "<td>"+v+"</td>";
            })
            tbl_body += "<tr>"+tbl_row+"</tr>";
          })

        return tbl_body;
      }

      function getSnowboardFilterOptions(){
        var opts = [];
        $checkboxes.each(function(){
          if(this.checked){
            opts.push(this.id);
          }
        });

        return opts;
      }

      function updateSnowboards(opts){
        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(records){
            $('#boards tbody').html(makeTable(records));
          }
        });
      }

      var $checkboxes = $("input:checkbox");
     $checkboxes.on("change", function(){
        var opts = getSnowboardFilterOptions();
        updateSnowboards(opts);
      });

      checkboxes.trigger("change");
</script>

最后我有了submit.php,其中包含用于选择正确内容的php代码。

<?php 
  $pdo = new PDO('mysql:host=localhost;dbname=...', '...', '...');
  $opts = $_POST['filterOpts'];
  $qMarks = str_repeat('?,', count($opts) - 1) . '?';
  $statement = $pdo->prepare("SELECT gender, price_range, brand, model, rocker_type, flex, size_range, image FROM snowboards)");
  $statement -> execute($opts);
  $results = $statement -> fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($results);
  echo($json);
?>

现在没有指定SELECT查询,因为我不知道如何。

如果有人知道我做错了什么,或者有更好的建议来解决它,请告诉你。

0 个答案:

没有答案