308

Simple PHP Shopping Cart using SESSION

 3 years ago
source link: https://www.codexworld.com/simple-php-shopping-cart-using-sessions/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Simple PHP Shopping Cart 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 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.

  • List the products on the webpage.
  • Custom shopping cart library.
  • Add multiple products to the cart.
  • Checkout cart items.
  • Preview and submit an order.

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

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

Create Database Tables

Minimum 4 database tables (products, customers, orders, and order_items) are needed 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,
 `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` enum('1','0') COLLATE utf8_unicode_ci 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` enum('1','0') COLLATE utf8_unicode_ci 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 that 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 class handles all the shopping cart-related operations. The methods of Cart class helps 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 it 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']);
    }
}

Database Configuration (dbConfig.php)

The following code is used to connect the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php 
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName     = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

Cart Requests Controller (cartAction.php)

The cartAction.php file handles all the action requested by the user from the web page. 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 Cart class.
    • After the successful operation, the user is redirected to the orderSuccess.php page.
<?php 
// Initialize shopping cart class
require_once 'Cart.class.php';
$cart = new Cart;

// Include the database config file
require_once 'dbConfig.php';

// Default redirect page
$redirectLoc = 'index.php';

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

// Get product details
        $query = $db->query("SELECT * FROM products WHERE id = ".$productID);
        $row = $query->fetch_assoc();
        $itemData = array(
            'id' => $row['id'],
            'name' => $row['name'],
            'price' => $row['price'],
            'qty' => 1
        );

// Insert item to cart
        $insertItem = $cart->insert($itemData);

// Redirect to cart page
        $redirectLoc = $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
        $redirectLoc = 'viewCart.php';
    }elseif($_REQUEST['action'] == 'placeOrder' && $cart->total_items() > 0){
        $redirectLoc = '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)){
            $errorMsg .= 'Please enter your email address.<br/>';
        }
        if(empty($phone)){
            $errorMsg .= 'Please enter your phone number.<br/>';
        }
        if(empty($address)){
            $errorMsg .= 'Please enter your address.<br/>';
        }

if(empty($errorMsg)){
            // Insert customer data in the database
            $insertCust = $db->query("INSERT INTO customers (first_name, last_name, email, phone, address) VALUES ('".$first_name."', '".$last_name."', '".$email."', '".$phone."', '".$address."')");

if($insertCust){
                $custID = $db->insert_id;

// Insert order info in the database
                $insertOrder = $db->query("INSERT INTO orders (customer_id, grand_total, created, status) VALUES ($custID, '".$cart->total()."', NOW(), 'Pending')");

if($insertOrder){
                    $orderID = $db->insert_id;

// Retrieve cart items
                    $cartItems = $cart->contents();

// Prepare SQL to insert order items
                    $sql = '';
                    foreach($cartItems as $item){
                        $sql .= "INSERT INTO order_items (order_id, product_id, quantity) VALUES ('".$orderID."', '".$item['id']."', '".$item['qty']."');";
                    }

// Insert order items in the database
                    $insertOrderItems = $db->multi_query($sql);

if($insertOrderItems){
                        // Remove all items from cart
                        $cart->destroy();

// Redirect to the status page
                        $redirectLoc = 'orderSuccess.php?id='.$orderID;
                    }else{
                        $sessData['status']['type'] = 'error';
                        $sessData['status']['msg'] = 'Some problem occurred, please try again.';
                    }
                }else{
                    $sessData['status']['type'] = 'error';
                    $sessData['status']['msg'] = 'Some problem occurred, please try again.';
                }
            }else{
                $sessData['status']['type'] = 'error';
                $sessData['status']['msg'] = 'Some problem occurred, please try again.';
            }
        }else{
            $sessData['status']['type'] = 'error';
            $sessData['status']['msg'] = 'Please fill all the mandatory fields.<br>'.$errorMsg; 
        }
        $_SESSION['sessData'] = $sessData;
    }
}

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

Bootstrap and jQuery Library

  • Bootstrap 4 library is used to design the product list, shopping cart, checkout form, and order status view.
  • 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)

In this page,

  • The products are fetched from the database and listed with the Add to Cart button.
  • Add to Cart button redirects the user to the cartAction.php page with addToCart request and respective product ID.
  • The cart summary is placed at the top of the page, it redirects the user to the shopping cart view page.
<?php 
// Initialize shopping cart class
include_once 'Cart.class.php';
$cart = new Cart;

// Include the database config file
require_once 'dbConfig.php';
?> <!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> </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':'Empty'; ?>)</a> </div> <!-- Product list --> <div class="row col-lg-12">         <?php
        // Get products from database
        $result = $db->query("SELECT * FROM products ORDER BY id DESC LIMIT 10");
        if($result->num_rows > 0){ 
            while($row = $result->fetch_assoc()){
        ?> <div class="card col-lg-4"> <div class="card-body"> <h5 class="card-title"><?php echo $row["name"]; ?></h5> <h6 class="card-subtitle mb-2 text-muted">Price: <?php echo '$'.$row["price"].' USD'; ?></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)

This page displays the cart items 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 item to the cart by Continue Shopping button or Checkout from cart.
  • Checkout button redirects the buyer to the checkout.php page to preview the order before submitting.
<?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"> <thead> <tr> <th width="45%">Product</th> <th width="10%">Price</th> <th width="15%">Quantity</th> <th class="text-right" width="20%">Total</th> <th width="10%"> </th> </tr> </thead> <tbody>                             <?php
                            if($cart->total_items() > 0){
                                // Get cart items from session
                                $cartItems = $cart->contents();
                                foreach($cartItems as $item){
                            ?> <tr> <td><?php echo $item["name"]; ?></td> <td><?php echo '$'.$item["price"].' USD'; ?></td> <td><input class="form-control" type="number" value="<?php echo $item["qty"]; ?>" onchange="updateCartItem(this, '<?php echo $item["rowid"]; ?>')"/></td> <td class="text-right"><?php echo '$'.$item["subtotal"].' USD'; ?></td> <td class="text-right"><button class="btn btn-sm btn-danger" onclick="return confirm('Are you sure?')?window.location.href='cartAction.php?action=removeCartItem&id=<?php echo $item["rowid"]; ?>':false;"><i class="itrash"></i> </button> </td> </tr> <?php } }else{ ?> <tr><td colspan="5"><p>Your cart is empty.....</p></td> <?php } ?> <?php if($cart->total_items() > 0){ ?> <tr> <td></td> <td></td> <td><strong>Cart Total</strong></td> <td class="text-right"><strong><?php echo '$'.$cart->total().' USD'; ?></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-light">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-lg btn-block btn-primary">Checkout</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 database config file
require_once 'dbConfig.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 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 '$'.$item["price"]; ?>(<?php echo $item["qty"]; ?>)</small> </div> <span class="text-muted"><?php echo '$'.$item["subtotal"]; ?></span> </li> <?php } } ?> <li class="list-group-item d-flex justify-content-between"> <span>Total (USD)</span> <strong><?php echo '$'.$cart->total(); ?></strong> </li> </ul> <a href="index.php" class="btn btn-block 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-lg 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(!isset($_REQUEST['id'])){
    header("Location: index.php");
}

// Include the database config file
require_once 'dbConfig.php';

// Fetch order details from database
$result = $db->query("SELECT r.*, c.first_name, c.last_name, c.email, c.phone FROM orders as r LEFT JOIN customers as c ON c.id = r.customer_id WHERE r.id = ".$_REQUEST['id']);

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 '$'.$orderInfo['grand_total'].' USD'; ?></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> </div> <!-- Order items --> <div class="row col-lg-12"> <table class="table table-hover"> <thead> <tr> <th>Product</th> <th>Price</th> <th>QTY</th> <th>Sub Total</th> </tr> </thead> <tbody>                         <?php
                        // Get order items from the database
                        $result = $db->query("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 = ".$orderInfo['id']);
                        if($result->num_rows > 0){ 
                            while($item = $result->fetch_assoc()){
                                $price = $item["price"];
                                $quantity = $item["quantity"];
                                $sub_total = ($price*$quantity);
                        ?> <tr> <td><?php echo $item["name"]; ?></td> <td><?php echo '$'.$price.' USD'; ?></td> <td><?php echo $quantity; ?></td> <td><?php echo '$'.$sub_total.' USD'; ?></td> </tr>                         <?php }
                        } ?> </tbody> </table> </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 easily enhance the functionality of the shopping cart script as per your needs.

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK