PHP Shopping Cart with MySQL using SESSION

The shopping cart functionality is an important part of every eCommerce project. It helps the user to select and purchase multiple items at once. Also, the online shopping cart allows viewing the selected items and the total price before submitting the order. If you want to build a simple PHP shopping cart from scratch, this step-by-step tutorial will help you a lot. In this tutorial, we’ll provide the complete guide and example code to create a simple shopping cart in PHP using SESSION and MySQL.

This example shopping cart script is designed in a way that can be implemented easily in PHP project and the tutorial makes it easy to understand the shopping cart concept in the web application. In our example script, we’ll use PHP session to store the products information in the cart. Once the order is submitted by the user, the products information would be inserted into the database using PHP and MySQL.

The following functionality will be implemented in the PHP Shopping Cart script.

  • Fetch products from the database and list them on the webpage.
  • Build a custom library to handle the shopping cart operations with PHP.
  • Add multiple products to the cart.
  • Checkout cart items.
  • Preview order summary and submit.

Before getting started take a look at the file structure of the PHP shopping cart script.

php_shopping_cart/
├── index.php
├── viewCart.php
├── checkout.php
├── orderSuccess.php
├── config.php
├── dbConnect.php
├── cartAction.php
├── Cart.class.php
├── js/
|   └── jquery.min.js
├── css/
|   ├── bootstrap.min.css
|   └── style.css
└── images/

Create Database Tables

Some tables are required in the database to store products, customers, and orders information. We will use 4 database tables (products, customers, orders, and order_items) to create a simple session-based shopping cart in PHP with MySQL.

The following SQL creates a products table to store the product information in the MySQL database.

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `price` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates a customers table to store the user contact information in the MySQL database.

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `address` text COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates an orders table in the MySQL database to store the order info submitted by the customer. The customer_id will be a FOREIGN KEY which is associated with the customers table.

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `grand_total` float(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `status` enum('Pending','Completed','Cancelled') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Pending',
  PRIMARY KEY (`id`),
  KEY `customer_id` (`customer_id`),
  CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The following SQL creates an order_items table to store the items of each order in the MySQL database. The order_id will be a FOREIGN KEY which is associated with the orders table.

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(5) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `order_id` (`order_id`),
  CONSTRAINT `order_items_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Cart Library (Cart.class.php)

The Cart library is a custom PHP that handles shopping cart-related operations. The methods of the Cart class help you to integrate shopping cart functionality in PHP.

  • contents() – Returns the entire cart content as an array.
  • get_item() – Returns a specific cart item details.
  • total_items() – Returns the total item count in cart.
  • total() – Returns the total price of the cart.
  • insert() – Insert items into the cart and save them in the SESSION.
  • update() – Update items in the cart.
  • remove() – Removes an item from the cart.
  • destroy() – Empty the cart and destroy the SESSION.
<?php 
// Start session
if(!session_id()){
    
session_start();
}

/**
 * Shopping Cart Class
 *
 * @package        PHP Library
 * @category    Shopping Cart
 * @author        CodexWorld Dev Team
 * @link        https://www.codexworld.com
 */
class Cart {
    protected 
$cart_contents = array();
    
    public function 
__construct(){
        
// get the shopping cart array from the session
        
$this->cart_contents = !empty($_SESSION['cart_contents'])?$_SESSION['cart_contents']:NULL;
        if (
$this->cart_contents === NULL){
            
// set some base values
            
$this->cart_contents = array('cart_total' => 0'total_items' => 0);
        }
    }
    
    
/**
     * Cart Contents: Returns the entire cart array
     * @param    bool
     * @return    array
     */
    
public function contents(){
        
// rearrange the newest first
        
$cart array_reverse($this->cart_contents);

        
// remove these so they don't create a problem when showing the cart table
        
unset($cart['total_items']);
        unset(
$cart['cart_total']);

        return 
$cart;
    }
    
    
/**
     * Get cart item: Returns a specific cart item details
     * @param    string    $row_id
     * @return    array
     */
    
public function get_item($row_id){
        return (
in_array($row_id, array('total_items''cart_total'), TRUE) OR ! isset($this->cart_contents[$row_id]))
            ? 
FALSE
            
$this->cart_contents[$row_id];
    }
    
    
/**
     * Total Items: Returns the total item count
     * @return    int
     */
    
public function total_items(){
        return 
$this->cart_contents['total_items'];
    }
    
    
/**
     * Cart Total: Returns the total price
     * @return    int
     */
    
public function total(){
        return 
$this->cart_contents['cart_total'];
    }
    
    
/**
     * Insert items into the cart and save it to the session
     * @param    array
     * @return    bool
     */
    
public function insert($item = array()){
        if(!
is_array($item) OR count($item) === 0){
            return 
FALSE;
        }else{
            if(!isset(
$item['id'], $item['name'], $item['price'], $item['qty'])){
                return 
FALSE;
            }else{
                
/*
                 * Insert Item
                 */
                // prep the quantity
                
$item['qty'] = (float) $item['qty'];
                if(
$item['qty'] == 0){
                    return 
FALSE;
                }
                
// prep the price
                
$item['price'] = (float) $item['price'];
                
// create a unique identifier for the item being inserted into the cart
                
$rowid md5($item['id']);
                
// get quantity if it's already there and add it on
                
$old_qty = isset($this->cart_contents[$rowid]['qty']) ? (int) $this->cart_contents[$rowid]['qty'] : 0;
                
// re-create the entry with unique identifier and updated quantity
                
$item['rowid'] = $rowid;
                
$item['qty'] += $old_qty;
                
$this->cart_contents[$rowid] = $item;
                
                
// save Cart Item
                
if($this->save_cart()){
                    return isset(
$rowid) ? $rowid TRUE;
                }else{
                    return 
FALSE;
                }
            }
        }
    }
    
    
/**
     * Update the cart
     * @param    array
     * @return    bool
     */
    
public function update($item = array()){
        if (!
is_array($item) OR count($item) === 0){
            return 
FALSE;
        }else{
            if (!isset(
$item['rowid'], $this->cart_contents[$item['rowid']])){
                return 
FALSE;
            }else{
                
// prep the quantity
                
if(isset($item['qty'])){
                    
$item['qty'] = (float) $item['qty'];
                    
// remove the item from the cart, if quantity is zero
                    
if ($item['qty'] == 0){
                        unset(
$this->cart_contents[$item['rowid']]);
                        return 
TRUE;
                    }
                }
                
                
// find updatable keys
                
$keys array_intersect(array_keys($this->cart_contents[$item['rowid']]), array_keys($item));
                
// prep the price
                
if(isset($item['price'])){
                    
$item['price'] = (float) $item['price'];
                }
                
// product id & name shouldn't be changed
                
foreach(array_diff($keys, array('id''name')) as $key){
                    
$this->cart_contents[$item['rowid']][$key] = $item[$key];
                }
                
// save cart data
                
$this->save_cart();
                return 
TRUE;
            }
        }
    }
    
    
/**
     * Save the cart array to the session
     * @return    bool
     */
    
protected function save_cart(){
        
$this->cart_contents['total_items'] = $this->cart_contents['cart_total'] = 0;
        foreach (
$this->cart_contents as $key => $val){
            
// make sure the array contains the proper indexes
            
if(!is_array($val) OR !isset($val['price'], $val['qty'])){
                continue;
            }
     
            
$this->cart_contents['cart_total'] += ($val['price'] * $val['qty']);
            
$this->cart_contents['total_items'] += $val['qty'];
            
$this->cart_contents[$key]['subtotal'] = ($this->cart_contents[$key]['price'] * $this->cart_contents[$key]['qty']);
        }
        
        
// if cart empty, delete it from the session
        
if(count($this->cart_contents) <= 2){
            unset(
$_SESSION['cart_contents']);
            return 
FALSE;
        }else{
            
$_SESSION['cart_contents'] = $this->cart_contents;
            return 
TRUE;
        }
    }
    
    
/**
     * Remove Item: Removes an item from the cart
     * @param    int
     * @return    bool
     */
     
public function remove($row_id){
        
// unset & save
        
unset($this->cart_contents[$row_id]);
        
$this->save_cart();
        return 
TRUE;
     }
     
    
/**
     * Destroy the cart: Empties the cart and destroy the session
     * @return    void
     */
    
public function destroy(){
        
$this->cart_contents = array('cart_total' => 0'total_items' => 0);
        unset(
$_SESSION['cart_contents']);
    }
}

Site and Database Configurations (config.php)

In the config.php file, some common and database settings are defined in constant variables.

Common constants:

  • CURRENCY – Specify the default currency code.
  • CURRENCY_SYMBOL – Specify the currency symbol.

Database constants:

  • DB_HOST – Specify the database host.
  • DB_USERNAME – Specify the database username.
  • DB_PASSWORD – Specify the database password.
  • DB_NAME – Specify the database name.
<?php 
// Common settings
define('CURRENCY''USD');
define('CURRENCY_SYMBOL''$');
 
// Database configuration 
define('DB_HOST''MySQL_Database_Host');
define('DB_USERNAME''MySQL_Database_Username');
define('DB_PASSWORD''MySQL_Database_Password');
define('DB_NAME''MySQL_Database_Name');

Database Connection (dbConnect.php)

The dbConnect.php file is used to connect and select the MySQL database using PHP.

<?php 
// Include the configuration file
require_once 'config.php';

// Connect with the database 
$db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME); 
 
// Display error if failed to connect 
if ($db->connect_errno) { 
    
printf("Connect failed: %s\n"$db->connect_error); 
    exit(); 
}

Cart Requests Controller (cartAction.php)

The cartAction.php file handles all the actions requested by the user from the web page UI. The code blocks would be executed based on the requested action.

  • addToCart
    • Fetch the product details from the database by the specified product ID and insert the item into the cart using Cart class.
    • After the successful operation, the user is redirected to the viewCart.php page.
  • updateCartItem – Update the cart by specific rowid using Cart class and returns the status message.
  • removeCartItem
    • Remove the item from the cart by the specific item id using Cart class.
    • After the successful operation, the user is redirected to the viewCart.php page.
  • placeOrder
    • Insert the customer data in the database.
    • Insert order in the database with the customer ID.
    • Insert the cart items data in the order_items table and link the order ID.
    • Remove the cart items from the SESSION using the Cart class.
    • After the successful operation, the user is redirected to the orderSuccess.php page.
<?php 
// Include the database connection file
require_once 'dbConnect.php';

// Initialize shopping cart class
require_once 'Cart.class.php';
$cart = new Cart;

// Default redirect page
$redirectURL 'index.php';

// Process request based on the specified action
if(isset($_REQUEST['action']) && !empty($_REQUEST['action'])){
    if(
$_REQUEST['action'] == 'addToCart' && !empty($_REQUEST['id'])){
        
$product_id $_REQUEST['id'];

        
// Fetch product details from the database
        
$sqlQ "SELECT * FROM products WHERE id=?";
        
$stmt $db->prepare($sqlQ);
        
$stmt->bind_param("i"$db_id);
        
$db_id $product_id;
        
$stmt->execute();
        
$result $stmt->get_result();
        
$productRow $result->fetch_assoc();

        
$itemData = array(
            
'id' => $productRow['id'],
            
'image' => $productRow['image'],
            
'name' => $productRow['name'],
            
'price' => $productRow['price'],
            
'qty' => 1
        
);
        
        
// Insert item to cart
        
$insertItem $cart->insert($itemData);
        
        
// Redirect to cart page
        
$redirectURL $insertItem?'viewCart.php':'index.php';
    }elseif(
$_REQUEST['action'] == 'updateCartItem' && !empty($_REQUEST['id'])){
        
// Update item data in cart
        
$itemData = array(
            
'rowid' => $_REQUEST['id'],
            
'qty' => $_REQUEST['qty']
        );
        
$updateItem $cart->update($itemData);
        
        
// Return status
        
echo $updateItem?'ok':'err';die;
    }elseif(
$_REQUEST['action'] == 'removeCartItem' && !empty($_REQUEST['id'])){
        
// Remove item from cart
        
$deleteItem $cart->remove($_REQUEST['id']);
        
        
// Redirect to cart page
        
$redirectURL 'viewCart.php';
    }elseif(
$_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0){
        
$redirectURL 'checkout.php';
        
        
// Store post data
        
$_SESSION['postData'] = $_POST;
    
        
$first_name strip_tags($_POST['first_name']);
        
$last_name strip_tags($_POST['last_name']);
        
$email strip_tags($_POST['email']);
        
$phone strip_tags($_POST['phone']);
        
$address strip_tags($_POST['address']);
        
        
$errorMsg '';
        if(empty(
$first_name)){
            
$errorMsg .= 'Please enter your first name.<br/>';
        }
        if(empty(
$last_name)){
            
$errorMsg .= 'Please enter your last name.<br/>';
        }
        if(empty(
$email) || !filter_var($emailFILTER_VALIDATE_EMAIL)){
            
$errorMsg .= 'Please enter a valid email.<br/>';
        }
        if(empty(
$phone)){
            
$errorMsg .= 'Please enter your contact number.<br/>';
        }
        if(empty(
$address)){
            
$errorMsg .= 'Please enter your address.<br/>';
        }
        
        if(empty(
$errorMsg)){
            
// Insert customer data into the database
            
$sqlQ "INSERT INTO customers (first_name,last_name,email,phone,address,created,modified) VALUES (?,?,?,?,?,NOW(),NOW())";
            
$stmt $db->prepare($sqlQ);
            
$stmt->bind_param("sssss"$db_first_name$db_last_name$db_email$db_phone$db_address);
            
$db_first_name $first_name;
            
$db_last_name $last_name;
            
$db_email $email;
            
$db_phone $phone;
            
$db_address $address;
            
$insertCust $stmt->execute();
            
            if(
$insertCust){
                
$custID $stmt->insert_id;
                
                
// Insert order info in the database
                
$sqlQ "INSERT INTO orders (customer_id,grand_total,created,status) VALUES (?,?,NOW(),?)";
                
$stmt $db->prepare($sqlQ);
                
$stmt->bind_param("ids"$db_customer_id$db_grand_total$db_status);
                
$db_customer_id $custID;
                
$db_grand_total $cart->total();
                
$db_status 'Pending';
                
$insertOrder $stmt->execute();
            
                if(
$insertOrder){
                    
$orderID $stmt->insert_id;
                    
                    
// Retrieve cart items
                    
$cartItems $cart->contents();
                    
                    
// Insert order items in the database
                    
if(!empty($cartItems)){
                        
$sqlQ "INSERT INTO order_items (order_id, product_id, quantity) VALUES (?,?,?)";
                        
$stmt $db->prepare($sqlQ);
                        foreach(
$cartItems as $item){
                            
$stmt->bind_param("ids"$db_order_id$db_product_id$db_quantity);
                            
$db_order_id $orderID;
                            
$db_product_id $item['id'];
                            
$db_quantity $item['qty'];
                            
$stmt->execute();
                        }
                        
                        
// Remove all items from cart
                        
$cart->destroy();
                        
                        
// Redirect to the status page
                        
$redirectURL 'orderSuccess.php?id='.base64_encode($orderID);
                    }else{
                        
$sessData['status']['type'] = 'error';
                        
$sessData['status']['msg'] = 'Something went wrong, please try again.';
                    }
                }else{
                    
$sessData['status']['type'] = 'error';
                    
$sessData['status']['msg'] = 'Something went wrong, please try again.';
                }
            }else{
                
$sessData['status']['type'] = 'error';
                
$sessData['status']['msg'] = 'Something went wrong, please try again.';
            }
        }else{
            
$sessData['status']['type'] = 'error';
            
$sessData['status']['msg'] = '<p>Please fill all the mandatory fields.</p>'.$errorMsg
        }
        
        
// Store status in session
        
$_SESSION['sessData'] = $sessData;
    }
}

// Redirect to the specific page
header("Location: $redirectURL");
exit();

Bootstrap and jQuery Library

We will use the Bootstrap 5 library to design the product list, shopping cart, checkout form, and order status UI.

  • The jQuery is used in the cart page to update cart items via AJAX.
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery library -->
<script src="js/jquery.min.js"></script>

Products list (index.php)

Initially, all the products are fetched from the database and listed on the web page.

  • Add to Cart button is attached to each product box.
  • Add to Cart button redirects the user to the cartAction.php page with action type (action=addToCart) and respective product ID (id).
  • The cart basket is placed at the top of the page to show the cart items summary. It redirects the user to the shopping cart view page.
<?php 
// Include the database connection file
require_once 'dbConnect.php';

// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;

// Fetch products from the database
$sqlQ "SELECT * FROM products";
$stmt $db->prepare($sqlQ);
$stmt->execute();
$result $stmt->get_result();
?> <!DOCTYPE html> <html lang="en"> <head> <title>PHP Shopping Cart</title> <meta charset="utf-8"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom style --> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>PRODUCTS</h1> <!-- Cart basket --> <div class="cart-view"> <a href="viewCart.php" title="View Cart"><i class="icart"></i> (<?php echo ($cart->total_items() > 0)?$cart->total_items().' Items':0?>)</a> </div> <!-- Product list --> <div class="row col-lg-12">     <?php
    
if($result->num_rows 0){
        while(
$row $result->fetch_assoc()){
            
$proImg = !empty($row["image"])?'images/products/'.$row["image"]:'images/demo-img.png';
    
?> <div class="card" style="width: 18rem;"> <img src="<?php echo $proImg?>" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"><?php echo $row["name"]; ?></h5> <h6 class="card-subtitle mb-2 text-muted">Price: <?php echo CURRENCY_SYMBOL.$row["price"].' '.CURRENCY?></h6> <p class="card-text"><?php echo $row["description"]; ?></p> <a href="cartAction.php?action=addToCart&id=<?php echo $row["id"]; ?>" class="btn btn-primary">Add to Cart</a> </div> </div> <?php } }else{ ?> <p>Product(s) not found.....</p> <?php ?> </div> </div> </body> </html>

Shopping Cart (viewCart.php)

Initially, all the cart items are listed in a tabular format.

  • The cart contents are retrieved from the SESSION using the Cart library and display the cart items with the total price.
  • The buyer can update or delete items from the shopping cart.
  • The buyer will be able to add more items to the cart by the Continue Shopping button or Checkout from the cart.
  • The Checkout button redirects the buyer to the checkout.php page to preview the order before submitting it.
<?php 
// Include the configuration file
require_once 'config.php';

// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;
?> <!DOCTYPE html> <html lang="en"> <head> <title>View Cart - PHP Shopping Cart</title> <meta charset="utf-8"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom style --> <link href="css/style.css" rel="stylesheet"> <!-- jQuery library --> <script src="js/jquery.min.js"></script> <script> function updateCartItem(obj,id){ $.get("cartAction.php", {action:"updateCartItem", id:id, qty:obj.value}, function(data){ if(data == 'ok'){ location.reload(); }else{ alert('Cart update failed, please try again.'); } }); } </script> </head> <body> <div class="container"> <h1>SHOPPING CART</h1> <div class="row"> <div class="cart"> <div class="col-12"> <div class="table-responsive"> <table class="table table-striped cart"> <thead> <tr> <th width="10%"></th> <th width="35%">Product</th> <th width="15%">Price</th> <th width="15%">Quantity</th> <th width="20%">Total</th> <th width="5%"> </th> </tr> </thead> <tbody>                         <?php
                        
if($cart->total_items() > 0){
                            
// Get cart items from session
                            
$cartItems $cart->contents();
                            foreach(
$cartItems as $item){
                                
$proImg = !empty($item["image"])?'images/products/'.$item["image"]:'images/demo-img.png';
                        
?> <tr> <td><img src="<?php echo $proImg?>" alt="..."></td> <td><?php echo $item["name"]; ?></td> <td><?php echo CURRENCY_SYMBOL.$item["price"].' '.CURRENCY?></td> <td><input class="form-control" type="number" value="<?php echo $item["qty"]; ?>" onchange="updateCartItem(this, '<?php echo $item["rowid"]; ?>')"/></td> <td><?php echo CURRENCY_SYMBOL.$item["subtotal"].' '.CURRENCY?></td> <td><button class="btn btn-sm btn-danger" onclick="return confirm('Are you sure to remove cart item?')?window.location.href='cartAction.php?action=removeCartItem&id=<?php echo $item["rowid"]; ?>':false;" title="Remove Item"><i class="itrash"></i> </button> </td> </tr> <?php } }else{ ?> <tr><td colspan="6"><p>Your cart is empty.....</p></td> <?php ?> <?php if($cart->total_items() > 0){ ?> <tr> <td></td> <td></td> <td></td> <td><strong>Cart Total</strong></td> <td><strong><?php echo CURRENCY_SYMBOL.$cart->total().' '.CURRENCY?></strong></td> <td></td> </tr> <?php ?> </tbody> </table> </div> </div> <div class="col mb-2"> <div class="row"> <div class="col-sm-12 col-md-6"> <a href="index.php" class="btn btn-block btn-secondary"><i class="ialeft"></i>Continue Shopping</a> </div> <div class="col-sm-12 col-md-6 text-right"> <?php if($cart->total_items() > 0){ ?> <a href="checkout.php" class="btn btn-block btn-primary">Proceed to Checkout<i class="iaright"></i></a> <?php ?> </div> </div> </div> </div> </div> </div> </body> </html>

Order Preview (checkout.php)

In the checkout page, the buyer can preview the selected products before submitting the order.

  • Display cart summary with the total price.
  • HTML Form to provide the contact information of the buyer.
  • Once the customer submits the order, the buyer’s contact details are submitted to the cartAction.php file with placeOrder request.
<?php 
// Include the configuration file
require_once 'config.php';

// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;

// If the cart is empty, redirect to the products page
if($cart->total_items() <= 0){
    
header("Location: index.php");
}

// Get posted form data from session
$postData = !empty($_SESSION['postData'])?$_SESSION['postData']:array();
unset(
$_SESSION['postData']);

// Get status message from session
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
if(!empty(
$sessData['status']['msg'])){
    
$statusMsg $sessData['status']['msg'];
    
$statusMsgType $sessData['status']['type'];
    unset(
$_SESSION['sessData']['status']);
}
?> <!DOCTYPE html> <html lang="en"> <head> <title>Checkout - PHP Shopping Cart Tutorial</title> <meta charset="utf-8"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom style --> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>CHECKOUT</h1> <div class="col-12"> <div class="checkout"> <div class="row"> <?php if(!empty($statusMsg) && ($statusMsgType == 'success')){ ?> <div class="col-md-12"> <div class="alert alert-success"><?php echo $statusMsg; ?></div> </div> <?php }elseif(!empty($statusMsg) && ($statusMsgType == 'error')){ ?> <div class="col-md-12"> <div class="alert alert-danger"><?php echo $statusMsg; ?></div> </div> <?php } ?> <div class="col-md-4 order-md-2 mb-4"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Your Cart</span> <span class="badge badge-secondary badge-pill"><?php echo $cart->total_items(); ?></span> </h4> <ul class="list-group mb-3">                     <?php
                    
if($cart->total_items() > 0){
                        
// Get cart items from session
                        
$cartItems $cart->contents();
                        foreach(
$cartItems as $item){
                    
?> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div> <h6 class="my-0"><?php echo $item["name"]; ?></h6> <small class="text-muted"><?php echo CURRENCY_SYMBOL.$item["price"]; ?>(<?php echo $item["qty"]; ?>)</small> </div> <span class="text-muted"><?php echo CURRENCY_SYMBOL.$item["subtotal"]; ?></span> </li> <?php } } ?> <li class="list-group-item d-flex justify-content-between"> <span>Total (<?php echo CURRENCY?>)</span> <strong><?php echo CURRENCY_SYMBOL.$cart->total(); ?></strong> </li> </ul> <a href="index.php" class="btn btn-sm btn-info">+ add items</a> </div> <div class="col-md-8 order-md-1"> <h4 class="mb-3">Contact Details</h4> <form method="post" action="cartAction.php"> <div class="row"> <div class="col-md-6 mb-3"> <label for="first_name">First Name</label> <input type="text" class="form-control" name="first_name" value="<?php echo !empty($postData['first_name'])?$postData['first_name']:''?>" required> </div> <div class="col-md-6 mb-3"> <label for="last_name">Last Name</label> <input type="text" class="form-control" name="last_name" value="<?php echo !empty($postData['last_name'])?$postData['last_name']:''?>" required> </div> </div> <div class="mb-3"> <label for="email">Email</label> <input type="email" class="form-control" name="email" value="<?php echo !empty($postData['email'])?$postData['email']:''?>" required> </div> <div class="mb-3"> <label for="phone">Phone</label> <input type="text" class="form-control" name="phone" value="<?php echo !empty($postData['phone'])?$postData['phone']:''?>" required> </div> <div class="mb-3"> <label for="last_name">Address</label> <input type="text" class="form-control" name="address" value="<?php echo !empty($postData['address'])?$postData['address']:''?>" required> </div> <input type="hidden" name="action" value="placeOrder"/> <input class="btn btn-success btn-block" type="submit" name="checkoutSubmit" value="Place Order"> </form> </div> </div> </div> </div> </div> </body> </html>

Order Success (orderSuccess.php)

Once the order is successfully submitted, the customer is redirected to this page.

  • Order details are fetched from the database based on the order ID passed in the URL.
  • Display the order and buyer information.
  • List the order items in a tabular format.
<?php 
if(empty($_REQUEST['id'])){
    
header("Location: index.php");
}
$order_id base64_decode($_REQUEST['id']);

// Include the database connection file
require_once 'dbConnect.php';

// Fetch order details from the database
$sqlQ "SELECT r.*, c.first_name, c.last_name, c.email, c.phone, c.address FROM orders as r LEFT JOIN customers as c ON c.id = r.customer_id WHERE r.id=?";
$stmt $db->prepare($sqlQ);
$stmt->bind_param("i"$db_id);
$db_id $order_id;
$stmt->execute();
$result $stmt->get_result();

if(
$result->num_rows 0){
    
$orderInfo $result->fetch_assoc();
}else{
    
header("Location: index.php");
}
?> <!DOCTYPE html> <html lang="en"> <head> <title>Order Status - PHP Shopping Cart</title> <meta charset="utf-8"> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom style --> <link href="css/style.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>ORDER STATUS</h1> <div class="col-12"> <?php if(!empty($orderInfo)){ ?> <div class="col-md-12"> <div class="alert alert-success">Your order has been placed successfully.</div> </div> <!-- Order status & shipping info --> <div class="row col-lg-12 ord-addr-info"> <div class="hdr">Order Info</div> <p><b>Reference ID:</b> #<?php echo $orderInfo['id']; ?></p> <p><b>Total:</b> <?php echo CURRENCY_SYMBOL.$orderInfo['grand_total'].' '.CURRENCY?></p> <p><b>Placed On:</b> <?php echo $orderInfo['created']; ?></p> <p><b>Buyer Name:</b> <?php echo $orderInfo['first_name'].' '.$orderInfo['last_name']; ?></p> <p><b>Email:</b> <?php echo $orderInfo['email']; ?></p> <p><b>Phone:</b> <?php echo $orderInfo['phone']; ?></p> <p><b>Address:</b> <?php echo $orderInfo['address']; ?></p> </div> <!-- Order items --> <div class="row col-lg-12"> <table class="table table-hover cart"> <thead> <tr> <th width="10%"></th> <th width="45%">Product</th> <th width="15%">Price</th> <th width="10%">QTY</th> <th width="20%">Sub Total</th> </tr> </thead> <tbody>                     <?php
                    
// Get order items from the database
                    
$sqlQ "SELECT i.*, p.name, p.price FROM order_items as i LEFT JOIN products as p ON p.id = i.product_id WHERE i.order_id=?";
                    
$stmt $db->prepare($sqlQ);
                    
$stmt->bind_param("i"$db_id);
                    
$db_id $order_id;
                    
$stmt->execute();
                    
$result $stmt->get_result();
                    
                    if(
$result->num_rows 0){ 
                        while(
$item $result->fetch_assoc()){
                            
$price $item["price"];
                            
$quantity $item["quantity"];
                            
$sub_total = ($price*$quantity);
                            
$proImg = !empty($item["image"])?'images/products/'.$item["image"]:'images/demo-img.png';
                    
?> <tr> <td><img src="<?php echo $proImg?>" alt="..."></td> <td><?php echo $item["name"]; ?></td> <td><?php echo CURRENCY_SYMBOL.$price.' '.CURRENCY?></td> <td><?php echo $quantity?></td> <td><?php echo CURRENCY_SYMBOL.$sub_total.' '.CURRENCY?></td> </tr> <?php } } ?> </tbody> </table> </div> <div class="col mb-2"> <div class="row"> <div class="col-sm-12 col-md-6"> <a href="index.php" class="btn btn-block btn-primary"><i class="ialeft"></i>Continue Shopping</a> </div> </div> </div> <?php }else{ ?> <div class="col-md-12"> <div class="alert alert-danger">Your order submission failed!</div> </div> <?php ?> </div> </div> </body> </html>

Shopping Cart Implementation in CodeIgniter

Conclusion

Hope this guide will help you to understand the basic shopping cart functionality in PHP with SESSION and MySQL. Using the PHP Cart library and this example code you’ll be able to implement a shopping cart in your web application instantly. Also, you can customize the design and enhance the functionality of the shopping cart script based on the website UI.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

40 Comments

  1. Rohan Said...
  2. Sarah Karamsi Said...
  3. Satish Pawar Said...
  4. Dre Said...
  5. Ponmalar Said...
  6. ELYAR SEMI Said...
  7. Imali Said...
  8. Bogus Name Said...
  9. Shawn Mckenzie Said...
  10. Chris Clement Said...
  11. Sebastien Plante Said...
  12. Kiran Said...
  13. Cath Said...
  14. Hell Is Rare Said...
  15. SRAVAN KUMAR Said...
  16. Website Dzyner Said...
  17. Tayyaba Said...
  18. Nick Said...
  19. Willy Said...
  20. Ajit Rajaram Chaware Said...
  21. Mahdev Prasad Said...
  22. Sid Said...
    • CodexWorld Said...
  23. Mimi Said...
    • CodexWorld Said...
  24. Kalai Said...
  25. Chris Said...
  26. Rishav Basu Said...
    • CodexWorld Said...
  27. Jstyles Said...
  28. Anu Said...
    • CodexWorld Said...
  29. Leon Yew Said...
  30. Johnny Said...
  31. Harold Rau Said...
  32. Satyanarayan Said...
    • CodexWorld Said...
  33. Zionsoft Said...
  34. Sami Said...

Leave a reply

keyboard_double_arrow_up