PHP Script for updating Shopping Cart

Displaying Cart to add, remove and update products
We update the session varaiable $_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.
$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);

Your Rating





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-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer