Simple Shopping Cart System in PHP

Simple Shopping Cart System in PHP

Shopping cart system is online store for your business globally. This tutorial is all about how to create simple shopping cart system in php. Here a shopping cart system which going to introduce to all of you is very simple. It is created in php and its functionality is based on session. It is customizable mean that anyone can customize as per their requirement. In this cart system quantity is added to product and price is based on quantity and its unit price. Cart system is totally based on session. The item added to cart is stored in session variable which can be removed by clearing session by click on empty cart button.

Shoppingcart system in PHP - PHPCluster
Shoppingcart system in PHP – PHPCluster

Demo

Add a Product To Cart

<ul class='products'>
<?php 
//call function using class object
$product_array= $db_handler->runquery("SELECT * FROM products");
if(!empty($product_array))
{
    foreach($product_array as $product) {
    ?>
<li class='product'>
<form method="POST" action="index.php?act=add&code=<?php echo $product["product_code"]; ?>">
<h3 style="background-color:blue;color:white;"><?=$product['product_name']?></h3>
<img src="<?=$product['image'] ?>" height="150" width="130">
Price:<?='Rs'.$product['price']?><br>
<input type="text" size="2" maxlength="2" name="product_quantity" value="1" /><br>
    <input type="hidden" name="product_name" value="<?=$product['product_name'] ?>"><br>
	<input type="hidden" name="product_code" value="<?=$product['product_code'] ?>" />
    <input type="hidden" name="price" value="<?=$product['price']?>"/>
	<input type="hidden" name="type" value="add" />
<input type="submit" name="cart" class="btn" value="Add to Cart">
</form>
</li>
<?php }?>

</ul>
<?php } ?>

Clear or Empty cart items

case "remove":
if(!empty($_SESSION["cart_item"]))
{
foreach($_SESSION["cart_item"] as $code=>$v){
if($_GET["code"]==$code)
unset($_SESSION["cart_item"][$code]);
}
if(empty($_SESSION["cart_item"]))
unset($_SESSION["cart_item"]);
}
break;
case "empty":
if(!empty($_SESSION["cart_item"]))
{
unset($_SESSION["cart_item"]);
}
break;
}}