PHP Shopping Cart without Database

A shopping cart application will have a catalog to showcase products as a gallery. The products can be stored in a database, file or any other forms as suitable to your business depending on the product list count. We have already seen many shopping cart example with the database to store products. In a persistent shopping cart example, we have used database tables to manage cart. If we want to sell a huge volume of products, we need database-like storage medium. Otherwise if count of products is lesser, we can simply manage products in a static way or by using files or arrays. Let us create a shopping cart application without a database by managing products using PHP array.

shopping

View Demo

I have created a Product class to define the product array and a function to return this array. I get the product by using this class and display them in a gallery. The gallery will contain the add-to-cart option for each product. After adding a product to the cart, it will be maintained in a PHP session indexed by the product code. The cart item in the session array will be listed to the user. The cart view contains individual cart delete and bulk delete actions. All the cart action are performed by using jQuery AJAX

Product Gallery and Cart HTML

I have designed the landing page with two main sections for the products and the cart. I iterate the product array and display each product in a card to showcase all the products in a gallery view. If the cart session is not empty, I run a loop through the PHP cart session array to display the list of cart items. The HTML code is,

<html lang="en">
<head>
<TITLE>PHP Shopping Cart without Database</TITLE>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <h1>Demo Shopping Cart without Database</h1>
    <?php 
	require_once "product-gallery.php";
    ?>
    <div class="clear-float"></div>
    <div id="shopping-cart">
        <div class="txt-heading">
            Shopping Cart <a id="btnEmpty" class="cart-action"
                onClick="cartAction('empty','');"><img
                src="images/icon-empty.png" /> Empty Cart</a>
        </div>
        <div id="cart-item">
        <?php 
		require_once "ajax-action.php";
        ?>
        </div>
    </div>
</body>
</html>

Get Product Array and Create Gallery

In the following code block, the Product class instance is created to get the product array. After getting the product array it is iterated to display each product card. The card element is marked with the product code to refer the product identity while performing the cart actions.

<?php
require_once ("Product.php");
$product = new Product();
$productArray = $product->getAllProduct();
?>
<div id="product-grid">
    <div class="txt-heading">Products</div>
<?php
if (! empty($productArray)) {
    foreach ($productArray as $k => $v) {
        ?>
		<div class="product-item">
        <form id="frmCart">
            <div class="product-image">
                <img src="<?php echo $productArray[$k]["image"]; ?>">
            </div>
            <div>
                <div class="product-info">
                    <strong><?php echo $productArray[$k]["name"]; ?></strong>
                </div>
                <div class="product-info product-price"><?php echo "$".$productArray[$k]["price"]; ?></div>
                <div class="product-info">
                    <button type="button"
                        id="add_<?php echo $productArray[$k]["code"]; ?>"
                        class="btnAddAction cart-action"
                        onClick="cartAction('add','<?php echo $productArray[$k]["code"]; ?>')">
                        <img src="images/add-to-cart.png" />
                    </button>
                    <input type="text"
                        id="qty_<?php echo $productArray[$k]["code"]; ?>"
                        name="quantity" value="1" size="2" />
                </div>
            </div>
        </form>
    </div>
	<?php
    }
}
?>
</div>

jQuery AJAX Cart Actions

This jQuery script contains the functions to perform the cart actions like add-to-cart, remove-single-cart-item and empty-cart. When the add-to-cart icon is clicked on the product card, the product will be added to the cart session with the product code reference. While adding a product to the cart, I checked whether the product is already added. If so, I will update only the quantity. Otherwise, I will create a new cart array instance.

From the list of existing cart session, we can remove particular cart item and also clear the cart completely. While removing a single item, the product code will be sent to the PHP to clear the particular item from the session.

<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script>
function cartAction(action, product_code) {
    var queryString = "";
    if (action != "") {
        switch (action) {
        case "add":
            queryString = 'action=' + action + '&code=' + product_code
                    + '&quantity=' + $("#qty_" + product_code).val();
            break;
        case "remove":
            queryString = 'action=' + action + '&code=' + product_code;
            break;
        case "empty":
            queryString = 'action=' + action;
            break;
        }
    }
    jQuery.ajax({
        url : "ajax-action.php",
        data : queryString,
        type : "POST",
        success : function(data) {
            $("#cart-item").html(data);
            if (action == "add") {
                $("#add_" + product_code + " img").attr("src",
                        "images/icon-check.png");
                $("#add_" + product_code).attr("onclick", "");
            }
        },
        error : function() {
        }
    });
}
</script>

PHP Code to Perform Cart Action

I created switch case in PHP to handle the cart add, remove-single, empty actions of the shopping cart. The action parameter is sent via the AJAX request. This parameter will be received in PHP and supply to the switch case. After performing the cart action, the latest cart session array is iterated to create the HTML to display the current cart status.

<?php
session_start();
require_once ("Product.php");
$product = new Product();
$productArray = $product->getAllProduct();
if(!empty($_POST["action"])) {
switch($_POST["action"]) {
	case "add":
		if(!empty($_POST["quantity"])) {
		    $productByCode = $productArray[$_POST["code"]];
		    $itemArray = array($productByCode["code"]=>array('name'=>$productByCode["name"], 'code'=>$productByCode["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode["price"]));
			
			if(!empty($_SESSION["cart_item"])) {
			    $cartCodeArray = array_keys($_SESSION["cart_item"]);
			    if(in_array($productByCode["code"],$cartCodeArray)) {
					foreach($_SESSION["cart_item"] as $k => $v) {
							if($productByCode["code"] == $k) {
							    $_SESSION["cart_item"][$k]["quantity"] = $_SESSION["cart_item"][$k]["quantity"]+$_POST["quantity"];
							}
					}
				} else {
					$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
				}
			} else {
				$_SESSION["cart_item"] = $itemArray;
			}
		}
	break;
	case "remove":
		if(!empty($_SESSION["cart_item"])) {
			foreach($_SESSION["cart_item"] as $k => $v) {
					if($_POST["code"] == $k)
						unset($_SESSION["cart_item"][$k]);
					if(empty($_SESSION["cart_item"]))
						unset($_SESSION["cart_item"]);
			}
		}
	break;
	case "empty":
		unset($_SESSION["cart_item"]);
	break;		
}
}
?>
<?php
if(isset($_SESSION["cart_item"])){
    $item_total = 0;
?>	
<table class="tutorial-table">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Code</strong></th>
<th class="align-right"><strong>Quantity</strong></th>
<th class="align-right"><strong>Price</strong></th>
<th></th>
</tr>	
<?php		
    foreach ($_SESSION["cart_item"] as $item){
		?>
				<tr>
				<td><strong><?php echo $item["name"]; ?></strong></td>
				<td><?php echo $item["code"]; ?></td>
				<td align="right"><?php echo $item["quantity"]; ?></td>
				<td align="right"><?php echo "$".$item["price"]; ?></td>
				<td align="center"><a onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction cart-action"><img src="images/icon-delete.png" /></a></td>
				</tr>
				<?php
        $item_total += ($item["price"]*$item["quantity"]);
		}
		?>

<tr>
<td colspan="3" align=right><strong>Total:</strong></td>
<td align=right><?php echo "$". number_format($item_total,2); ?></td>
<td></td>
</tr>
</tbody>
</table>		
  <?php
}
?>

PHP Product Class

This PHP class contains a property to define the product array. The initialized class property will be returned by its function named as getAllProduct(). This function is called with the Product class instance from the product gallery page.

<?php

class Product
{

    public $productArray = array(
        "3DcAM01" => array(
            'id' => '1',
            'name' => '3D Camera',
            'code' => '3DcAM01',
            'image' => 'product-images/camera.jpg',
            'price' => '1500.00'
        ),
        "USB02" => array(
            'id' => '2',
            'name' => 'External Hard Drive',
            'code' => 'USB02',
            'image' => 'product-images/external-hard-drive.jpg',
            'price' => '800.00'
        ),
        "wristWear03" => array(
            'id' => '3',
            'name' => 'Wrist Watch',
            'code' => 'wristWear03',
            'image' => 'product-images/watch.jpg',
            'price' => '300.00'
        )
    );

    public function getAllProduct()
    {
        return $this->productArray;
    }
}

PHP Shopping Cart without Database Output

This screenshot shows the output of the shopping cart example without a database. It shows tick mark on a product cart to represent that it is currently added to the cart session. After page refresh, this tick mark will go and we can add more products to the cart.

php-shopping-cart-without-database 

View DemoDownload

This PHP code tutorial was published on April 25, 2018.

↑ Back to Top