如何在每次执行mysql查询时添加新的html表行

时间:2016-10-09 15:26:26

标签: php html mysql

我想知道是否可以查询数据库,并且每次单击提交按钮时,它都会向表中添加新行,而不是刷新页面。

你知道,当我运行查询时,它会成功添加行,但是当我再次运行查询时,它将刷新页面,基本上只能一次添加一行。

基本上,我希望能够创建一个表,每次使用条形码扫描器扫描条形码时,该表都会将产品添加到列表中。当用户扫描代码时,查询将执行以从数据库中获取相关数据,并显示一行。

$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();

2 个答案:

答案 0 :(得分:0)

You can use jQuery/ajax to achieve this. Check out this post. I believe it has exactly what you're looking for: Creating a table with mysql, php and ajax (with jquery)

答案 1 :(得分:0)

You can do this Using Ajax

I'm writing an Psudo code which will give you and idea how to do this

Step 1: create a table and define table Id

<table id="myTable">
<tr>
    <td><strong>ID</strong></td>
    <td><strong>Name</strong></td>
    </tr>
</table>

Step 2: Submit Your Barcode Data or product Id using Ajax

<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>

Step 3: your getProduct.php Code will be like this

$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();