How to Create a Simple Shopping Cart with PHP and MySQL

11 months ago admin PHP

In this tutorial, we will see how to create a simple shopping cart with PHP and MySQL, so I assume that you have already a database with the products to display and you already know how to connect and fetch data from Mysql Databases.


Create the home page

First, we create the home page here we display all the products as I said I assume that you have already done this step so here I am using just static data.

                                                        
                                                                                                                        
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PHP Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
  </head>
  <body class="bg-light">
    <div class="container">
        <div class="row my-5">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-body">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th scope="col">#</th>
                                    <th scope="col">Product Name</th>
                                    <th scope="col">Price</th>
                                    <th scope="col">Qty</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <th scope="row">1</th>
                                    <td>Iphone</td>
                                    <td>$1200</td>
                                    <form action="cart.php" method="post">
                                        <td style="width: 15%">
                                            <input type="number" class="form-control" min="1" name="qty" value="1">
                                        </td>
                                        <td>
                                            <input type="hidden" name="id" value="1">
                                            <input type="hidden" name="name" value="Iphone">
                                            <input type="hidden" name="price" value="1200">
                                            <button class="btn btn-sm btn-primary" type="submit" name="add_to_cart">
                                                Add to Cart
                                            </button>
                                        </td>
                                    </form>
                                </tr>
                                <tr>
                                    <th scope="row">2</th>
                                    <td>Samsung</td>
                                    <td>$1000</td>
                                    <form action="cart.php" method="post">
                                        <td style="width: 15%">
                                            <input type="number" class="form-control" min="1" name="qty" value="1">
                                        </td>
                                        <td>
                                            <input type="hidden" name="id" value="2">
                                            <input type="hidden" name="name" value="Samsung">
                                            <input type="hidden" name="price" value="1000">
                                            <button class="btn btn-sm btn-primary" type="submit" name="add_to_cart">
                                                Add to Cart
                                            </button>
                                        </td>
                                    </form>
                                </tr>
                                <tr>
                                    <th scope="row">3</th>
                                    <td>Lenovo</td>
                                    <td>$400</td>
                                    <form action="cart.php" method="post">
                                        <td style="width: 15%">
                                            <input type="number" class="form-control" min="1" name="qty" value="1">
                                        </td>
                                        <td>
                                            <input type="hidden" name="id" value="3">
                                            <input type="hidden" name="name" value="Lenovo">
                                            <input type="hidden" name="price" value="400">
                                            <button class="btn btn-sm btn-primary" type="submit" name="add_to_cart">
                                                Add to Cart
                                            </button>
                                        </td>
                                    </form>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
  </body>
</html>

Create the cart.php file

Next, we create the cart.php file here we receive the product to add to the cart, and we check if it already exists we increment only the quantity if not we add the product to the cart.

Also, we fetch & display all the products from the cart and we have a button to remove a selected product from the cart.

                                                            
                                                                                                                                
<?php
session_start();
// Get data when user click on add to cart
if (isset($_POST['add_to_cart'])) {
    // Add data to array
    $product = array(
        'id' => $_POST['id'],
        'name' => $_POST['name'],
        'price' => $_POST['price'],
        'qty' => $_POST['qty']
    );

    // Check if the cart already exists if yes
    // We proceed if not
    // We create the cart 
    if (!isset($_SESSION['cart'])) {
        $_SESSION['cart'] = array();
        $_SESSION['cart'][] = $product;
    } else {
        $productExists = false;
        foreach ($_SESSION['cart'] as $key => $cartItem) {
            // Check if the product is already in the cart if yes
            // We increment the quantity
            if ($cartItem['id'] === $product['id']) {
                $_SESSION['cart'][$key] = $product;
                $productExists = true;
            }
        }

        // If the product does not exists we add it to the cart
        if (!$productExists) {
            $_SESSION['cart'][] = $product;
        }
    }
}

// When the user click on remove item
if (isset($_GET['remove'])) {
    $productId = $_GET['remove'];

    // Find the product in the cart  and remove
    foreach ($_SESSION['cart'] as $key => $product) {
        if ($product['id'] === $productId) {
            unset($_SESSION['cart'][$key]);
        }
    }
    $_SESSION['cart'] = array_values($_SESSION['cart']);
}
?>
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>PHP Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
  </head>
  <body class="bg-light">
    <div class="container">
        <div class="row my-5">
            <div class="col-md-8 mx-auto">
                <div class="card">
                    <div class="card-header bg-white d-flex justify-content-between">
                        <h3 class="my-2">
                            Shopping Cart
                        </h3>
                        <a href="index.php" class="btn btn-link">
                            Home 
                        </a>
                    </div>
                    <div class="card-body">
                        <?php 
                            // Display the products in the cart 
                            if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {     
                                echo '<table class="table">';
                                echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Action</th></tr>';
                                foreach ($_SESSION['cart'] as $item) {
                                    echo '<tr>';
                                    echo '<td>' . $item['id'] . '</td>';
                                    echo '<td>' . $item['name'] . '</td>';
                                    echo '<td>$' . $item['price'] . '</td>';
                                    echo '<td>' . $item['qty'] . '</td>';
                                    echo '<td><a class="btn btn-sm btn-danger" href="cart.php?remove=' . $item['id'] . '">Remove</a></td>';
                                    echo '</tr>';
                                }
                                echo '</table>';
                            } else {
                                echo '<div class="alert alert-info">Your shopping cart is empty.</div>';
                            }
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
  </body>
</html>

Related Tuorials

How to Sort Associative Arrays in Descending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the key...


How to Sort Associative Arrays in Ascending Order According to the Key Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the key v...


How to Sort Associative Arrays in Descending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in descending order according to the valu...


How to Sort Associative Arrays in Ascending Order According to the Value in PHP

in this lesson, we will see how to sort associative arrays in ascending order according to the value...


How Do you Sort an Array in Descending Order in PHP

In this lesson, we will see how to sort descending an array in PHP, we will use the rsort() function...


How to Sort Ascending an Array in PHP

In this lesson, we will see how to sort ascending an array in PHP, we will use the sort() function t...


How to Remove a Key and its Value from an Associative Array in PHP

In this lesson, we will see how to remove a key and its value from an associative array in PHP,&nbsp...


How to Modify a Value in an Associative Array in PHP

In this lesson, we will see how to modify a value in an associative array in PHP, an Associative arr...


How to Add an Item to an Associative Array in PHP

In this lesson, we will see how to add an item to an associative array in PHP, an Associative array...


How to Add an Element to an Array in PHP

In this lesson, we will see how to add an element to an array in PHP, PHP has a built-in function th...