Shopping cart – PHP | Cookies

In this tutorial, we will teach you how you can create a shopping cart in PHP using cookies.

  • We will be using Bootstrap for design.
  • We have created a link which when clicked will open the cart page where all items added in cart will be displayed.
  • First we will display all products from database, so we have created a connection with database, fetch all products using PHP and MySQL.
  • To check if item is already added in cart, we have to get all the cart items. We are storing shopping cart in cookies, and we can only store string values in cookies. So we will return the current cart if exists, if not exists then we will start with an empty array.
  • Then we will loop (while loop) through all the products from database, and inside that loop we will run another loop (foreach loop) to check if the item already exists in cart. Boolean variable $flag will tell if the item already exists in cart or not.
  • We are displaying product name and price from database. You might also have product image as well.
  • Then we will create a form for deleting the product from cart if the item already exists. It will have product unique ID (productCode in our case) as hidden field. Othewise, we will create a form to add product in cart. It will also have product ID along with quantity, by default 1 quantity.

index.php

<!-- include bootstrap -->
<link rel="stylesheet" href="bootstrap.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="bootstrap.js"></script>

<div class="container" style="margin-top: 50px;">

    <!-- link to open cart page -->
    <div class="row">
        <div class="col-md-6">
            <a href="cart.php" class="btn btn-link">
                Cart
            </a>
        </div>
    </div>

    <div class="row">
        <?php
        // connect with database
        $conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");
        
        // get all products
        $result = mysqli_query($conn, "SELECT * FROM products");

        // get cookie cart
        $cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
        $cart = json_decode($cart);

        // loop through all cart items
        while ($row = mysqli_fetch_object($result))
        {
            // check if product already exists in cart
            $flag = false;
            foreach ($cart as $c)
            {
                if ($c->productCode == $row->productCode)
                {
                    $flag = true;
                    break;
                }
            }
            ?>

            <div class="col-md-3" style="margin-bottom: 20px;">
                <div class="card" style="height: 200px;">
                    <div class="card-body">
                        <h5 class="card-title">
                            <?php echo $row->productName; ?>
                        </h5>
                        <p class="card-text">
                            <?php echo $row->buyPrice; ?>
                        </p>

                        <?php if ($flag) { ?>

                            <!-- show delete button if already exists -->

                            <form method="POST" action="delete-cart.php">
                                <input type="hidden" name="productCode" value="<?php echo $row->productCode; ?>">
                                <input type="submit" class="btn btn-danger" value="Delete from cart">
                            </form>

                        <?php } else { ?>

                            <!-- add to cart -->

                            <form method="POST" action="add-cart.php">
                                <input type="hidden" name="quantity" value="1">
                                <input type="hidden" name="productCode" value="<?php echo $row->productCode; ?>">
                                <input type="submit" class="btn btn-primary" value="Add to cart">
                            </form>

                        <?php } ?>

                    </div>
                </div>
            </div>

            <?php
        }
        ?>
    </div>
</div>

If you run the code now, you will be able to view all products from database along with button to add cart. As we havn’t added any product in cart yet so it will not display the delete button.

all-products-using-php-mysql
all-products-using-php-mysql

Time to add the products in shopping cart using PHP cookies.

add-cart.php

Create a new file named add-cart.php. In this file:

  • We will connect with database and fetch product’s data using it’s ID. Because we will storing product’s information in cart as well.
  • We are getting the current cookie array and push the new product in it along with it’s quantity.
  • Then we will save the cookie using the setcookie(name, value) function.
  • As cookies can only be saved in string, so we are converting the PHP Array into JSON string using json_encode($array) function.
  • And finally redirecting the user back to home page where all products are being displayed.
<?php

$conn = mysqli_connect("localhost:8889", "root", "root", "classicmodels");

$quantity = $_POST["quantity"];
$productCode = $_POST["productCode"];

$cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$cart = json_decode($cart);

$result = mysqli_query($conn, "SELECT * FROM products WHERE productCode = '" . $productCode . "'");
$product = mysqli_fetch_object($result);

array_push($cart, array(
    "productCode" => $productCode,
    "quantity" => $quantity,
    "product" => $product
));

setcookie("cart", json_encode($cart));
header("Location: index.php");

?>

If you run the code now and click on “add cart” button on any product, you will see its text change to “delete from cart”.

added-in-cart-php-cookies
added-in-cart-php-cookies

If you click on delete button, you will see an error for file not found because we havn’t created that file yet, too obvious 🙂

delete-cart.php

Create a new file named delete-cart.php. In this file:

  • We are getting the product ID and all items from cart.
  • Create a new array which will have all the products except the one selected for deletion.
  • Then we will update the cookie with new array, having all the other products other than the deleted product.
  • And redirecting back to home page.
<?php

$productCode = $_POST["productCode"];

$cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$cart = json_decode($cart);

$new_cart = array();
foreach ($cart as $c)
{
    if ($c->productCode != $productCode)
    {
        array_push($new_cart, $c);
    }
}

setcookie("cart", json_encode($new_cart));
header("Location: index.php");

?>

Now if you run the code, you will see once you click on delete button that text will be changed back to “add to cart”. That is because the product is being deleted from cart using cookies. Now we need to show all cart items on a separate page usually called “Cart” 🙂

cart.php

Create a new file named cart.php. We already have a link to this file. In this file:

  • Get all the cart items from cookies using PHP.
  • Create 2 forms, 1 to delete the product, and second to update the quantity of product.
  • We already have an implementation for deleting the product from cart.
  • In update form, we will create a quantity field which user can change. And a hidden field for product ID.
  • We are also displaying the total of all cart items by multiplying the product price by the quantity (product price * quantity = total)
<link rel="stylesheet" href="bootstrap.css">
<script src="jquery-3.3.1.min.js"></script>
<script src="bootstrap.js"></script>

<div class="container" style="margin-top: 50px;">

    <?php
    $cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
    $cart = json_decode($cart);

    $total = 0;

    foreach ($cart as $c)
    {
        $total += $c->product->buyPrice * $c->quantity;
        ?>
        <div class="row">
            <div class="col-md-12">
                <div class="card" style="height: 200px;">
                    <div class="card-body">
                        <h5 class="card-title"><?php echo $c->product->productName; ?></h5>
                        <p class="card-text"><?php echo $c->product->buyPrice * $c->quantity; ?></p>

                        <form method="POST" action="delete-cart.php" style="float: right; margin-left: 10px;">
                            <input type="hidden" name="productCode" value="<?php echo $c->productCode; ?>">
                            <button type="submit" class="btn btn-danger">
                                x
                            </button>
                        </form>

                        <form method="POST" action="update-cart.php" style="float: right;">
                            <input type="number" name="quantity" min="1" value="<?php echo $c->quantity; ?>">
                            <input type="hidden" name="productCode" value="<?php echo $c->productCode; ?>">
                            <input type="submit" class="btn btn-warning" value="Update">
                        </form>

                    </div>
                </div>
            </div>
        </div>

        <?php
    }
    ?>

    <p>
        <?php echo $total; ?>
    </p>

</div>

If you run the code now, you will see a list of all cart items added along with update and delete button:

Shopping cart - PHP
Shopping cart – PHP

Try to change the quantity of any product and hit “update”, it will redirect you to a page where shopping cart needs to be updated.

update-cart.php

Create a new file named update-cart.php. In this file:

  • We are searching for that product using it’s ID.
  • When found, we are updating it’s quantity value with the new one.
  • And finally updating the cookie using PHP and redirecting back to home page.
<?php

$productCode = $_POST["productCode"];
$quantity = $_POST["quantity"];

$cart = isset($_COOKIE["cart"]) ? $_COOKIE["cart"] : "[]";
$cart = json_decode($cart);

foreach ($cart as $c)
{
    if ($c->productCode == $productCode)
    {
        $c->quantity = $quantity;
    }
}

setcookie("cart", json_encode($cart));
header("Location: cart.php");

We know that you might be following this in your current working project and every project has a different scenario. So if you face any problem in following this, feel free to ask in the comments section below.

[wpdm_package id=’487′]

4 Replies to “Shopping cart – PHP | Cookies”

  1. Thanks for sharing your thoughts. I really appreciate your efforts and I am waiting for your next post thank
    you once again.

  2. Hey! Would you mind if I share your blog with my facebook group?
    There’s a lot of folks that I think would really enjoy your content.
    Please let me know. Many thanks

Comments are closed.