I was wondering if it is possible to query a database, and each time a submit button is clicked, it will add a new row to the table, instead of refreshing the page.
You see, what's happening is that when I run the query, it will add the row successfully, but when I run the query again, it will refresh the page, essentially only being able to add only one row at a time.
Basically, I want to be able to create a table which will add a product to the list each time I scan a barcode with a barcode scanner. As the user scans the code, the query will execute to grab the relevant data from the database, and display a row.
$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();
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)
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.