[英]How to add a new html table row each time mysql query is executed
我想知道是否可以查询数据库,并且每次单击提交按钮时,都会向表中添加新行,而不是刷新页面。
您会发现,发生的事情是,当我运行查询时,它将成功添加行,但是当我再次运行查询时,它将刷新页面,本质上一次只能添加一行。
基本上,我希望能够创建一个表,该表将在每次使用条形码扫描仪扫描条形码时将产品添加到列表中。 当用户扫描代码时,将执行查询以从数据库中获取相关数据,并显示一行。
$barcode = $_POST["Barcode"]; $query = "Select * from products WHERE ProductBarcode = $barcode"; $result = $mysqli->query($query); if ($result->num_rows > 0) { echo "<table> <tr> <td><strong>ID</strong></td> <td><strong>Name</strong></td> </tr>"; // output data of each row while($row = $result->fetch_assoc()) { echo "<tr><td><input type='checkbox' value='".$row['Row_ID']."' />".$row['Row_ID']."</td> <td>".$row['ProductName']." "."</td></tr>"; } echo "</table>"; } else { echo "0 results"; } $mysqli->close();
您可以使用jQuery / ajax实现此目的。 看看这篇文章。 我相信它正是您要寻找的东西: 使用mysql,php和ajax(使用jquery)创建表
您可以使用Ajax做到这一点
我正在编写一个伪代码,它将为您提供想法
步骤1:建立表格并定义表格编号
<table id="myTable">
<tr>
<td><strong>ID</strong></td>
<td><strong>Name</strong></td>
</tr>
</table>
第2步:使用Ajax提交条形码数据或产品ID
<script>
$(document).on('click', "#submitButton", function () {
var barcode = $("#barcode").val();
$.ajax({
url: 'getProduct.php',
dataType: 'json',
type: 'POST',
data: {'Barcode':barcode},
success: function (data) {
if (data.products.length > 0) {
$(data.products).each(function(index,element){
$("#myTable").append("<tr><td><input type='checkbox' value='"+ element.product_id+"' />"+ element.product_id+"</td>
<td>"+ element.product_name+"</td></tr>");
});
} else {
alert("No Products Found");
}
},
beforeSend: function () {
showLoader();
},
complete: function () {
hideLoader();
},
});
});
</script>
步骤3:您的getProduct.php代码将如下所示
$barcode = $_POST["Barcode"];
$query = "Select * from products WHERE ProductBarcode = $barcode";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
$products = mysqli_fetch_all ($result, MYSQLI_ASSOC);
} else {
$products = [];
}
echo json_encode($products);
$mysqli->close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.