$p_id=$_POST['p_id'];
$qty=$_POST['qty'];
Data validation is done by setting Flags
$elements=array("msg"=>"","size_of_cart"=>"0","validation_status"=>"T");
if(!is_numeric($p_id)){$elements['validation_status']="F";
$elements['msg'].="Data Error";}
if(!is_numeric($qty)){$elements['validation_status']="F";
$elements['msg'].="Data Error";}
If the validation is cleared then Session status is checked, if it is not there then new session is created.
if($elements['validation_status']=='T'){
if(isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
//echo " session is available ";
}else{
//echo " session is not available ";
$_SESSION['cart']=array();
}
....
....
}
If the product id is already there then the product is removed first.
foreach ($_SESSION['cart'] as $key => $val) {
if($p_id=== $_SESSION['cart'][$key]['p_id']){
unset($_SESSION['cart'][$key]); // Remove the product
}
}
If quantity is not equal to zero then add the product with new quantity.
if($qty !=0){
$b=array("p_id"=>"$p_id","qty"=>$qty);
array_push($_SESSION['cart'],$b); // Items added to cart
$elements['msg'].="Product Added : p_id: $p_id , qty = $qty ";
}else{
$elements['msg'].="Product Removed : p_id: $p_id ";
}
We need to find out the total number of products in the cart after all above transactions are completed. This data we will send to front end script as we have to update the data at top right side of the page.
$elements['size_of_cart']=sizeof($_SESSION['cart']);
At the end we will send the JSON output to our front end script.
echo json_encode($elements);
plus2-cart-v1: Shopping Cart Script Display cart Products
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.