【发布时间】: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,而不是手动构建查询。它们由PDO 或MySQLi 提供。永远不要相信任何形式的输入!即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data。 Escaping is not enough!