We update the session variable $_SESSION['cart'] using PHP script. This page ( add.php ) will receive product_id and quantity against each product and update the cart.
DEMO : Shopping Cart Script with Add remove products →
add.php The backend PHP script
The PHP code inside add.php first receive the data Product id (p_id) and quantity ( qty ) from front end script.
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.
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.