PHP Script for updating Shopping Cart

Displaying Cart to add, remove and update products
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.

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.
Data validation is done by setting Flags

$elements['msg'].="Data Error";}
$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(isset($_SESSION['cart']) && !empty($_SESSION['cart'])) {
	//echo " session  is available ";

	//echo " session is not available ";
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){
array_push($_SESSION['cart'],$b); // Items added to cart
$elements['msg'].="Product Added : p_id: $p_id , qty = $qty ";
$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.
At the end we will send the JSON output to our front end script.
echo json_encode($elements);

Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here .

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer