$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 ScriptDisplay cart Products
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.