Create a MySQL table to store products
Columns are:
- product_id - It is the unique product_id (primary key) and auto incremented
- product_name - Name of the product
- price - Price of the product
- stock - Available stock
CREATE TABLE `product` (
`product_id` int(11) NOT NULL,
`product_name` varchar(200) NOT NULL,
`price` decimal(12,2) NOT NULL,
`stock` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `product` (`product_id`, `product_name`, `price`, `stock`) VALUES
(1, 'Sofa', '10000.00', 34),
(2, 'Dining Table', '6000.00', 100),
(3, 'Dining Chair(set of 4)', '5000.00', 30),
(4, 'Mattress', '8000.00', 111);
ALTER TABLE `product`
ADD PRIMARY KEY (`product_id`);
ALTER TABLE `product`
MODIFY `product_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
Create Add/Update product forms (index.php)
In index.php, we have an html table to show the list of existing products (Read). In the same screen, we also have an "Add" (Create) form and an "Update" (Update) form . An overview of index.php is given below:
- Show a list of products in an html table.
- For each product displayed, show edit and delete options. For updating the product, call the same program (index.php) with the product id and an edit flag as parameters. Call a JavaScript function to delete the product using Ajax.
- When no flag is set, show the "Add" product form
Display Product List (Read operation)
Let me show the code for displaying list of products in index.php.
It is a simple html table where we display details of each product using a for loop after fetching the data from the database. Let's see the code.
<h4>Product List</h4>
<div class="table-responsive" id="products">
<table class="table table-bordered table-striped">
<tr>
<thead>
<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr"></span>)</th><th>Stock</th><th>Action</th>
</thead>
</tr>
<?php
$select = "select * from product order by product_id";
$products = mysqli_query($conn,$select);
$counter = 0;
if (mysqli_num_rows($products) >0)
{
foreach ($products as $product_row) {
$counter++;
$product_id = $product_row['product_id'];
$product_name= $product_row['product_name'];
?>
<tr>
<td><?php echo $counter;?></td>
<td><?php echo $product_row['product_id'];?></td>
<td><?php echo $product_row['product_name'];?></td>
<td><?php echo $product_row['price'];?></td>
<td><?php echo $product_row['stock'];?></td>
<td>
<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>
<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
</td>
</tr>
<?php }
}
else { ?>
<tr><td colspan="7">No Products found</td></tr>
<?php } ?>
</table>
</div>
In the last column, we are using an Action to update and delete a product. For delete, a JavaScript function delProduct() is used.
If the edit flag is set, we will display the "Update" form. If no flag is set, we will display the "Add" form. See the code below:
<?php
include "cfg/dbconnect.php";
$product_id = $p_id = $p_name = $price = $stock = $flag = "";
$product_found = false;
if (isset($_REQUEST['flag']) && $_REQUEST['flag'] == 'edit'){
$flag = $_REQUEST['flag'];
if (isset($_REQUEST['id'])) {
$p_id = $_REQUEST['id'];
$sql = "select * from product where product_id='$p_id'";
$rs = mysqli_query($conn,$sql);
if (mysqli_num_rows($rs) > 0) {
$product_found = true;
$row=mysqli_fetch_array($rs);
$p_name = $row['product_name'];
$price = $row['price'];
$stock = $row['stock'];
}
}
}
?>
<?php if ($flag == "edit" && $product_found == true) { // Update Product Form ?>
<div class="col-md-4">
<h4>Update Product</h4>
<form id ="frm">
<input type="hidden" name="product_id" id="product_id" value="<?php echo $p_id;?>">
<div class="form-group col-md-12">
<label>Product Name</label>
<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255" value="<?php echo $p_name;?>">
<div class="error" id="product_err"></div>
</div>
<div class="form-group col-md-12">
<label>Price</label>
<input type = "number" name="price" id="price" class="form-control" min=".01" max="9999.99" step ="any" value="<?php echo $price;?>">
<div class="error" id="price_err"></div>
</div>
<div class="form-group col-md-12">
<label>Stock</label>
<input type = "number" name="stock" id="stock" class="form-control" min="0" value="<?php echo $stock;?>">
<div class="error" id="stock_err"></div>
</div>
<div class="col-md-12 text-right">
<a href ="index.php" class="btn btn-danger">Cancel</a>
<input type ="button" class="btn btn-primary" onclick="updateProduct()" value="Save">
</div>
</form>
</div>
<?php } else { // Add Product Form ?>
<div class="col-md-4">
<h4>Add Product</h4>
<form id ="frm">
<div class="form-group col-md-12">
<label>Product Name</label>
<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255">
<div class="error" id="product_err"></div>
</div>
<div class="form-group col-md-12">
<label>Price</label>
<input type = "number" name="price" id="price" class="form-control" min=".01" max="9999.99" step ="any">
<div class="error" id="price_err"></div>
</div>
<div class="form-group col-md-12">
<label>Stock</label>
<input type = "number" name="stock" id="stock" class="form-control" min="0">
<div class="error" id="stock_err"></div>
</div>
<div class="col-md-12 text-right">
<input type ="button" class="btn btn-primary" onclick="addProduct()" value="Add">
</div>
</form>
</div>
<?php } ?>
Note the save button in line 44. On the Onclick event of this button, we call a JavaScript function updateProduct(). This function will use Ajax to update the product details in the database. It is defined in product.js and we will explain it soon.
When the edit flag is not available, we display the "Add Product" form, see line 48. We call addProduct() function to add a product using Ajax. Below is the complete code of index.php.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Products</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" media="all"/>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Add, Update and Delete Product using Ajax</h2>
<div id="showMsg"></div>
<?php
include "cfg/dbconnect.php";
$product_id = $p_id = $p_name = $price = $stock = $flag = "";
$product_found = false;
if (isset($_REQUEST['flag']) && $_REQUEST['flag'] == 'edit') {
$flag = $_REQUEST['flag'];
if (isset($_REQUEST['id'])) {
$p_id = $_REQUEST['id'];
$sql = "select * from product where product_id='$p_id'";
$rs = mysqli_query($conn,$sql);
if (mysqli_num_rows($rs) > 0) {
$product_found = true;
$row=mysqli_fetch_array($rs);
$p_name = $row['product_name'];
$price = $row['price'];
$stock = $row['stock'];
}
}
}
?>
<div class="row">
<div class="col-md-8">
<h4>Product List</h4>
<div class="table-responsive" id="products">
<table class="table table-bordered table-striped">
<tr>
<thead>
<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr"></span>)</th><th>Stock</th><th>Action</th>
</thead>
</tr>
<?php
$select = "select * from product order by product_id";
$products = mysqli_query($conn,$select);
$counter = 0;
if (mysqli_num_rows($products) >0)
{
foreach ($products as $product_row) {
$counter++;
$product_id = $product_row['product_id'];
$product_name= $product_row['product_name'];
?>
<tr>
<td><?php echo $counter;?></td>
<td><?php echo $product_row['product_id'];?></td>
<td><?php echo $product_row['product_name'];?></td>
<td><?php echo $product_row['price'];?></td>
<td><?php echo $product_row['stock'];?></td>
<td>
<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>
<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
</td>
</tr>
<?php }
}
else { ?>
<tr><td colspan="7">No Products found</td></tr>
<?php } ?>
</table>
</div>
</div>
<?php if ($flag == "edit" && $product_found == true) { // Update Product Form ?>
<div class="col-md-4">
<h4>Update Product</h4>
<form id ="frm">
<input type="hidden" name="product_id" id="product_id" value="<?php echo $p_id;?>">
<div class="form-group col-md-12">
<label>Product Name</label>
<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255" value="<?php echo $p_name;?>">
<div class="error" id="product_err"></div>
</div>
<div class="form-group col-md-12">
<label>Price</label>
<input type = "number" name="price" id="price" class="form-control" min=".01" max="9999.99" step ="any" value="<?php echo $price;?>">
<div class="error" id="price_err"></div>
</div>
<div class="form-group col-md-12">
<label>Stock</label>
<input type = "number" name="stock" id="stock" class="form-control" min="0" value="<?php echo $stock;?>">
<div class="error" id="stock_err"></div>
</div>
<div class="col-md-12 text-right">
<a href ="index.php" class="btn btn-danger">Cancel</a>
<input type ="button" class="btn btn-primary" onclick="updateProduct()" value="Save">
</div>
</form>
</div>
<?php } else { // Add Product Form ?>
<div class="col-md-4">
<h4>Add Product</h4>
<form id ="frm">
<div class="form-group col-md-12">
<label>Product Name</label>
<input type = "text" name="p_name" id = "p_name" class="form-control" maxlength="255">
<div class="error" id="product_err"></div>
</div>
<div class="form-group col-md-12">
<label>Price</label>
<input type = "number" name="price" id="price" class="form-control" min=".01" max="9999.99" step ="any">
<div class="error" id="price_err"></div>
</div>
<div class="form-group col-md-12">
<label>Stock</label>
<input type = "number" name="stock" id="stock" class="form-control" min="0">
<div class="error" id="stock_err"></div>
</div>
<div class="col-md-12 text-right">
<input type ="button" class="btn btn-primary" onclick="addProduct()" value="Add">
</div>
</form>
</div>
<?php } ?>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="js/product.js"></script>
</body>
</html>
jQuery Ajax code (product.js)
We have used three JavaScript functions - addProduct(), updateProduct() and delProduct(). In each of these functions, we will use add_product.php, update_product.php and delete_product.php with Ajax requests.
Function addProduct()
This function is called when the user clicks on the "Add" button to add a new product.
function addProduct() {
var p_name = $('#p_name').val();
var price = $('#price').val();
var stock = $('#stock').val();
if (!validateData(p_name,price,stock))
return false;
$.ajax({
url:"add_product.php",
method:"POST",
data:{p_name:p_name, price:price,stock:stock},
dataType:"text",
success:function(response) {
$("#products").html(response);
}
});
}
- url: add_product.php - this will use the form values and insert into product table. Also, it will refresh the list of products.
- type: "POST" - post method is used.
- data: {p_name:p_name, price:price,stock:stock} - send the form values.
- dataType: "text" - response from Ajax will be in text format.
Now, let's see the code of add_product.php. It simply takes the input values and checks if product name already exists in database. If the product does not exist, it will insert a row in the "product" table.
<?php
include "cfg/dbconnect.php";
$err_msg = $succ_msg = "";
$p_name = trim($_POST['p_name']);
$price = $_POST['price'];
$stock = $_POST['stock'];
// check if same product name already exists
$sql = "select * from product where product_name = '$p_name'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) > 0)
$err_msg = "Product already exists";
else {
$sql = "insert into product (product_name,price,stock) values('$p_name', '$price', '$stock')";
$result = mysqli_query($conn,$sql);
if ($result)
$succ_msg = "Product Added";
else
$err_msg = "Error: Could not add Product";
}
?>
<table class="table table-bordered table-striped">
<tr>
<thead>
<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr">)</th><th>Stock</th><th>Action</th>
</thead>
</tr>
<?php
$select = "select * from product order by product_id";
$products = mysqli_query($conn,$select);
$counter = 0;
if (mysqli_num_rows($products) >0){
foreach ($products as $product_row) {
$counter++;
$product_id = $product_row['product_id'];
$product_name= $product_row['product_name'];?>
<tr>
<td><?php echo $counter;?></td>
<td><?php echo $product_row['product_id'];?></td>
<td><?php echo $product_row['product_name'];?></td>
<td><?php echo $product_row['price'];?></td>
<td><?php echo $product_row['stock'];?></td>
<td>
<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>
<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
</td>
</tr>
<?php }
}
else { ?>
<tr><td colspan="7">No Products found</td></tr>
<?php } ?>
</table>
<script>
<?php if (!empty($succ_msg)) {?>
$('#showMsg').html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $succ_msg;?></div>");
clearValues();
<?php }
if (!empty($err_msg)) {?>
$('#showMsg').html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $err_msg;?></span");
<?php } ?>
</script>
Function updateProduct()
This function is called when the user clicks on the "Save" button from the update form. It will validate the form and use Ajax to execute update_product.php. Let's see the code for this function.
function updateProduct() {
var product_id = $('#product_id').val();
var p_name = $('#p_name').val();
var price = $('#price').val();
var stock = $('#stock').val();
if (!validateData(p_name,price,stock))
return false;
if ($("#frm").data("changed")) {
$.ajax({
url:"update_product.php",
method:"POST",
data:{product_id:product_id, p_name:p_name, price:price,stock:stock},
dataType:"text",
success:function(response) {
$("#products").html(response);
}
});
}
else {
alert("No changes to save");
return false;
}
}
If form data is changed, we are executing Ajax in line 10. Note that product_id is the hidden field in the update form.
Now, let's see the code of update_product.php. It gets the input values and checks if another product with the same name already exists in the database. If another product with the same name does not exist, it updates the "product" table with the details of the product.
<?php
include "cfg/dbconnect.php";
$err_msg = $succ_msg = "";
$product_id = $_POST['product_id'];
$p_name = trim($_POST['p_name']);
$price = $_POST['price'];
$stock = $_POST['stock'];
// check if same product name already exists
$sql = "select * from product where product_name = '$p_name' and product_id <> '$product_id'";
$result = mysqli_query($conn,$sql);
if (mysqli_num_rows($result) >0)
$err_msg = "Product already exists";
else {
$sql = "update product set product_name = '$p_name',price = '$price',stock = '$stock' where product_id='$product_id'";
$result = mysqli_query($conn,$sql);
if ($result)
$succ_msg = "Product Updated";
else
$err_msg = "Error: Could not update Product";
}
?>
<table class="table table-bordered table-striped">
<tr>
<thead>
<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr">)</th><th>Stock</th><th>Action</th>
</thead>
</tr>
<?php
$select = "select * from product order by product_id";
$products = mysqli_query($conn,$select);
$counter = 0;
if (mysqli_num_rows($products) >0)
{
foreach ($products as $product_row) {
$counter++;
$product_id = $product_row['product_id'];
$product_name= $product_row['product_name'];?>
<tr>
<td><?php echo $counter;?></td>
<td><?php echo $product_row['product_id'];?></td>
<td><?php echo $product_row['product_name'];?></td>
<td><?php echo $product_row['price'];?></td>
<td><?php echo $product_row['stock'];?></td>
<td>
<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>
<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
</td>
</tr>
<?php }
}
else { ?>
<tr><td colspan="7">No Products found</td></tr>
<?php } ?>
</table>
<script>
// to display success or error message
<?php if (!empty($succ_msg)) {?>
$('#showMsg').html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $succ_msg;?></div>");
clearValues();
<?php }
if (!empty($err_msg)) {?>
$('#showMsg').html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $err_msg;?></span");
<?php } ?>
$("#frm").data("changed",false);
</script>
Function delProduct(product_id, product_name)
This function is called when the user clicks on the "delete" link from the list of products. This will take the input parameters product_id and product_name.
function delProduct(product_id, product_name){
if (confirm("Are you sure you want to delete product - "+product_name+"?")){
$.ajax({
url:"delete_product.php",
method:"POST",
data:{product_id:product_id},
dataType:"text",
success:function(response) {
$("#products").html(response);
}
});
}
}
Now, let's see the code of delete_product.php. It works the same way as add and update. It takes the input parameter product_id and deletes the product from the "product" table.
<?php
include "cfg/dbconnect.php";
$product_id = $_POST['product_id'];
$sql = "delete from product where product_id='$product_id'";
$result = mysqli_query($conn,$sql);
if ($result)
$succ_msg = "Product Deleted";
else
$err_msg = "Error: Could not delete Product";
?>
<table class="table table-bordered table-striped">
<tr>
<thead>
<th>Serial No.</th><th>Product Id</th><th>Product Name</th><th>Price (<span class="fa fa-inr">)</th><th>Stock</th><th>Action</th>
</thead>
</tr>
<?php
$select = "select * from product order by product_id";
$products = mysqli_query($conn,$select);
$counter = 0;
if (mysqli_num_rows($products) >0)
{
foreach ($products as $product_row) {
$counter++;
$product_id = $product_row['product_id'];
$product_name= $product_row['product_name'];?>
<tr>
<td><?php echo $counter;?></td>
<td><?php echo $product_row['product_id'];?></td>
<td><?php echo $product_row['product_name'];?></td>
<td><?php echo $product_row['price'];?></td>
<td><?php echo $product_row['stock'];?></td>
<td>
<a class="fa fa-edit" title="Edit" href="index.php?id=<?php echo $product_id;?>&flag=edit"></a>
<a class="fa fa-remove" title="Delete" href="javascript:void(0)" onClick="delProduct('<?php echo $product_id;?>','<?php echo $product_name;?>')"></a>
</td>
</tr>
<?php }
}
else { ?>
<tr><td colspan="7">No Products found</td></tr>
<?php } ?>
</table>
<script>
<?php if (!empty($succ_msg)) {?>
$('#showMsg').html("<div class='alert alert-success alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $succ_msg;?></div>");
clearValues();
<?php }
if (!empty($err_msg)) {?>
$('#showMsg').html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button><?= $err_msg;?></span");
<?php } ?>
</script>
Function validateData()
validateData() function is called by addProduct() and updateProduct() functions in product.js. This function is used to validate the form.
function validateData(p_name,p_price,p_stock){
if (p_name.trim() =="") {
$("#product_err").text("Product Name must have a value");
return false;
}
if (p_price.trim() == "") p_price = 0;
if(p_price <= 0)
{
$("#price_err").html("Enter a positive value for price");
$("#price").focus();
return false;
}
if (p_stock.trim() == "") {
$("#stock_err").html("Stock should be zero or positive");
$("#stock").focus();
return false;
}
if (p_stock <0) {
$("#stock_err").html("Stock should be zero or positive");
$("#stock").focus();
return false;
}
return true;
}
2 Thoughts on "PHP AJAX CRUD Tutorial: Create, Read, Update, Delete Without Page Reload"
Post a Comment