【问题标题】:Pass a Select Form to database to populate the Datatable将选择表单传递给数据库以填充数据表
【发布时间】:2021-12-29 21:39:05
【问题描述】:

我真的不知道如何将表单传递给数据表。

我正在尝试创建一个选择表单,该表单将用作我的 WHERE 子句来对数据库进行查询以填充数据表。这是我当前的代码。

Index.php

<form method="POST" id="frm">
<select name="selectplace">
    <option value="PLACE 1">PLACE 1</option>
    <option value="PLACE 2">PLACE 2</option>
    <option value="PLACE 3">PLACE 3</option>
</select>
<button type="submit" name="submitPlace">SUBMIT</button>
          <div class="table-responsive">
            <table class="table table-bordered table-striped text-center" id="place-table">
              <thead>
                <tr>
                  <th>PLACE #</th>
                  <th>PLACE NAME</th>
                  <th>TOTAL VISITORS</th>
                </tr>
              </thead>
              <tfoot>
                 <tr>
                  <th>PLACE #</th>
                  <th>PLACE NAME</th>
                  <th>TOTAL VISITORS</th>
                </tr>
              </tfoot>
            </table>
          </div>

用于数据表的 JQUERY

       $(document).ready(function() {
      $('#place-table').DataTable({
        "ajax": {
          url: "json.php",
          "dataSrc": "",
            "data": function(d) {
            var frm_data = $('frm').serializeArray();
           $.each(frm_data, function(key, val) {
           d[val.name] = val.value;
   });
 }
        },
        columns: [{
          data: 'place_id',
        }, {
          data: 'place_name',
        }, {
          data: 'total_visitor',
        }]
      });
    });
  </script>

json.php


这是我想传递表单的地方,所以我可以将它用作我的 WHERE 子句
<?php 
  $selectedplace = $_POST['selectedplace'];
  $sql = "SELECT * FROM placestable WHERE $selectedplace";
    $result = mysqli_query($conn, $sql);
    $data = array();
    while($row = mysqli_fetch_assoc($result)) {
        $data[] = array(
            "id"=>$row['id'],
            "place_name"=> $row['place_name'],
            "total_visitor"=> $row['total_visitor'],
        );
    }
    echo json_encode($data); //before was: echo json_encode(array('data' => $data));
     ?>

【问题讨论】:

  • var frm_data = $('frm').serializeArray(); - 任何地方都没有带有 标签名称 frm 的元素。如果要按 ID 选择元素,则需要 # 前缀。
  • 警告:您对SQL Injections 持开放态度,应该使用参数化的prepared statements,而不是手动构建查询。它们由PDOMySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your dataEscaping is not enough!

标签: php jquery datatable


【解决方案1】:

首先,您需要在提交表单时从数据表重新加载 ajax。您可以使用 jquery 提交事件并重新渲染 ajax,如下所示:

$("#idForm").submit(function(e) {
   e.preventDefault();

   table.ajax.reload() 
});

别忘了把你的数据表赋值给table变量

 var table = $('#place-table').DataTable({....})
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多