How To Make A Shopping Cart Using PHP (SESSION)

How To Make A Shopping Cart Using PHP (SESSION)

How To Make A Shopping Cart Using PHP (SESSION)

0 Sales

Free

The functionality of the shopping cart is an important part of any eCommerce project. Selecting and buying multiple items at once benefits the user. The online shopping cart also helps you to see the selected items before sending the order and the total price. This step-by-step tutorial will help you a lot if you want to build a simple PHP shopping cart from scratch. Using SESSION and MySQL, we will provide the complete guide and example code in this tutorial to create a simple shopping cart in PHP.

 

This shopping cart script example is designed to be easily incorporated in the PHP project and tutorial makes it easy to understand the concept of shopping cart in the web application. We will use PHP session to store product information in the cart in our example script. Use PHP and MySQL to insert the product information into the database once the order is submitted by the user.

 

In the PHP Shopping Cart, the following features will be introduced.

 

  • List on the web page of the products.

  • Custom cart library for shopping.

  • Add to the cart multiple products.

  • Products from the checkout bag.

  • Preview the order and apply it.


 

Until you start, take a look at PHP shopping cart script's files structure.

 

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

 

To create a simple session-based shopping cart in PHP with MySQL, a minimum of 4 database tables (items, customers, orders, and order items) are needed.

 

The following SQL generates a table of products to store information about the product 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 generates a table of customers to store in the MySQL server the client contact information.

 

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 generates a table of orders in the MySQL server to store the customer's order details. The customer I d is going to be a FOREIGN KEY connected to the list of customers.

 

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 a table of order items to store the items in the MySQL database for each order. The order I d is going to be a FOREIGN KEY associated with the table of orders.

 

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 group manages all the operations relevant to the shopping cart. Cart class methods help you integrate the functionality of shopping carts in PHP.

 

  • Contents() –Returns the whole content of the cart as an array.

  • Get item() –Returns the details of the specific item of the cart.

  • Total items() –Returns the total number of items in the box.

  • Tota() –Returns the cart's total price.

  • Insert() –Load and save things in the SESSION in the cart.

  • Update() –Update cart items.

  • Remove() –Delete the product from the cart.

  • Destroy() –Remove the SESSION from the cart.


 

<?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)


 

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

 

<?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 file cartAction.php manages all the action from the web page requested by the user. The blocks of code would be executed depending on the action demanded.

 

  1. AddToCart–

 

    • Use the Cart class to collect the product details from the server using the specified product ID and add the item into the cart.

 

    • The client will be guided to the viewCart.php site after the successful operation.


 

  1. UpdateCartItem – Update the rowid chart using the Cart class and return the status message.

 

  1. RemoveCartItem–

 

  • Using Cart class to remove the item from the cart using the specific item I d.

  • The user will be redirected to the viewCart.php page after the successful operation.

 

  1. PlaceOrder –

 

  • Insert the database customer data.

  • Add order with the customer ID in the server. 

  • Enter the data of the cart items into the order items table and attach the order ID. 

  • Remove the items from the SESSION using Cart class.

  • The client will be guided to the orderSuccess.php site after the successful operation.

 

<?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 designs the item list, the shopping cart, the checkout type and the status view of the order.

  • JQuery is used to update cart products using AJAX on the cart page.

 

<!-- 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,

  • From the server, the items are collected and described with the Add to Cart key.

  • Add to Cart button redirects the user to the cartAction.php page with an application for addToCart and the corresponding item ID.

  • The cart overview is placed at the top of the page and redirects the user to the shopping cart display 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 shows the items of the cart in a tabular format.

 

  • Using the Cart collection, the cart contents are retrieved from the SESSION and show the total price of the cart objects.

  • The buyer will be able to update or remove items from the shopping cart.

  • Using the Continue Shopping button or cart checkout, the buyer will be able to add more item to the cart.

  • To preview the order before submitting, the checkout button redirects the buyer to the checkout.php page.


 

<?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)

Until submitting the order, the customer will preview the selected items on the checkout page.

 

  • Display the total price of the cart summary.

  • HTML Form to provide the purchaser's contact information.

  • Once the customer submits the order, the contact details of the purchaser will be sent withplaceOrder application to the cartAction.php folder.

 

<?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)

When the order has been submitted successfully, the customer will be redirected to this page.

 

  • Based on the order ID passed in the URL, order information are retrieved from the server.

  • Show information about the order and the buyer.

  • List the items of the order 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>

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0