Simple PHP Shopping Cart

In this tutorial, we are going to see a simple PHP example for creating a shopping cart application. This shopping cart application is purposely kept simple and as minimal as possible. You can download this and quickly customize it for your needs. In this example, we are displaying a list of products from the database. For each product, we can select product quantity and add to cart. The cart items are stored in the session. The cart can be emptied by removing the items from the session.

php-shopping-cart

View Demo

Adding Products  to Shopping Cart

First, we need to create our product catalog page by listing products from the database. The following code retrieves the list of products from the database and displays them in a grid view. Each product has the ‘Add to cart’ option to place it into the cart.

<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) { 
foreach($product_array as $key=>$value){
?>
<div class="product-item">
	<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
	<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
	<div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
	<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
	<div><input type="text" name="quantity" value="1" size="2" /><input type="submit" value="Add to cart" class="btnAddAction" /></div>
	</form>
</div>
<?php }} ?>

On clicking the ‘Add to cart’ button, we add the selected product id and its quantity into a shopping cart. We are using PHP SESSION to store the cart items. The following code shows a switch case used for adding products to the cart. If we add the same product multiple times in a cart then the cart item quantity will be incremented.

case "add":
	if(!empty($_POST["quantity"])) {
		$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
		$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));
		
		if(!empty($_SESSION["cart_item"])) {
			if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) {
				foreach($_SESSION["cart_item"] as $k => $v) {
						if($productByCode[0]["code"] == $k) {
							if(empty($_SESSION["cart_item"][$k]["quantity"])) {
								$_SESSION["cart_item"][$k]["quantity"] = 0;
							}
							$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
						}
				}
			} else {
				$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
			}
		} else {
			$_SESSION["cart_item"] = $itemArray;
		}
	}
break;

Removing or Clearing Cart Item

In this example, we allow users to remove each item from the cart by using the ‘Remove Item’ link in each row. Also, we let the users clear the whole cart by using ‘Empty Cart’ option. On clicking ‘Remove Item’, we call remove action with the reference of the item code to clear the particular item of the cart session. We use PHP unset() to clear the cart session. The following code shows the switch cases used to perform ‘Remove Item’ and ‘Empty Cart’ actions.

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

Import the following SQL script for creating a product table and load your own data to show in your catalog page.

CREATE TABLE IF NOT EXISTS `tblproduct` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `code` varchar(255) NOT NULL,
  `image` text NOT NULL,
  `price` double(10,2) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_code` (`code`)
)

View DemoDownload

This PHP code tutorial was published on October 26, 2014.

↑ Back to Top