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.
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/
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;
This Cart class is a custom PHP library that handles shopping cart-related operations. The methods of the Cart library help you to integrate shopping cart functionality in PHP with SESSION.
<?php
/**
* Shopping Cart Class
*
* @package PHP Library
* @category Shopping Cart
* @author CodexWorld Dev Team
* @link https://www.codexworld.com
*/
if(!session_id()){ // Start session if not already started
session_start();
}
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']);
}
}
?>
In the config.php
file, some currency and database settings are defined in constant variables.
Currency constants:
Database constants:
<?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');
// Start session
if(!session_id()){
session_start();
}
?>
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_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Display error if failed to connect
if ($db->connect_errno) {
printf("Connect failed: %s\n", $db->connect_error);
exit();
}
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.
viewCart.php
page.rowid
using Cart class and returns the status message.viewCart.php
page.order_items
table and link the order ID.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($email, FILTER_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();
We will use the Bootstrap 5 library to design the product list, shopping cart, checkout form, and order status UI.
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery library -->
<script src="js/jquery.min.js"></script>
Initially, all the products are fetched from the database and listed on the web page.
cartAction.php
page with action type (action=addToCart
) and respective product ID (id
).<?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>
Initially, all the cart items are listed in a tabular format.
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>
In the checkout page, the buyer can preview the selected products before submitting the order.
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>
Once the order is successfully submitted, the customer is redirected to this page.
<?php
// Include the database connection file
require_once 'dbConnect.php';
if(!empty($_REQUEST['id'])){
$order_id = base64_decode($_REQUEST['id']);
// 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){
$orderData = $result->fetch_assoc();
}
}
if(empty($orderData)){
header("Location: index.php");
exit();
}
?>
<!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($orderData)){ ?>
<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 $orderData['id']; ?></p>
<p><b>Total:</b> <?php echo CURRENCY_SYMBOL.$orderData['grand_total'].' '.CURRENCY; ?></p>
<p><b>Placed On:</b> <?php echo $orderData['created']; ?></p>
<p><b>Buyer Name:</b> <?php echo $orderData['first_name'].' '.$orderData['last_name']; ?></p>
<p><b>Email:</b> <?php echo $orderData['email']; ?></p>
<p><b>Phone:</b> <?php echo $orderData['phone']; ?></p>
<p><b>Address:</b> <?php echo $orderData['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
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
Firstly thank you for this – helps me a lot. I would like to find out is it possible to add the same product as different entries in the cart? Reason being is I’m selling shirts and people need to select a product and the shirt size. I managed to get that working but whenever I add product 1 in small as an example and then add the same product again it just increases the quantity of that product
Hi
how can I implement this in my HTML shopping page already designed?
Thank you…!
how to add images to product and shopping cart???
Thank you so much…u help me a lot…
hi !
how to add user_id and product images ?
Thank you for this
Hi I need to limit the number of items a user can add to the cart, so if they try add more than 6 it won’t allow them and it triggers a message “number of items limited to 6”
This tutorial is very informative and resourceful.
However, the “add to cart” button per product, when you click it, it immediately goes to the next page of shopping cart.
For better user experiences, is there any way that you could multiple select your product first and only then check out on time to the next page of shopping cart?
I recently bought this code and hope to connect with Paypal. Can you shed some light? Others have asked this above but I see no replies.
Please see this tutorial – https://www.codexworld.com/paypal-standard-payment-gateway-integration-php/
Forget what I said on the other message, It’s all good ! 🙂
Really Appreciate this and Thanks to post this valuable code………………..
really appreciate this, but do you also have a code that controls the quantity in mysql database ?
hello, thank you for the great tutorial
how would you display all submitted orders in a single page in html tables (a table for each order_id that displays product details)
if possible can you explain how to display image of the product in viewCart page and address form in checkout page as well
Thank you so much for posting such a good tutorial session. Please could you let us know how to send cart email notification to customers with all the order details? We don’t have a payment gateway.
Items are not add in my cart
kindly help me
How to add & display image of a product please ?
Hi, congratulations on the script! I would like to update the product cart with features such as color and size … is it possible? Thank you
how to display count of product
Great work sir. How can I combine both Product page and Shopping Cart page to a single page. I.e., The shopping cart will appear either below or side of the Products container.
how to display item id on cart ?
Use the following code to display the item ID.
Hello there, can i have some help with displaying the shipping details for the current user , because in this code the session sessCustomerID is set to 1 which for me always displays that one user with his shipping details , and when i log in as another user the shipping details of the customer with id 1 are displayed, and not for the current user.How to manage that ,i would be really grateful if anybody can help me.
For example purpose, we have set
sessCustomerID
to 1. But you need to assign the logged in user ID insessCustomerID
.Hi,
Can you please help me connect the payment method to database please
How would you delete all the things in the cart at one time?
sir how to display the total cost in the orderSuccess page
Use the following code to get the order total cost in the orderSuccess.php file.
Thanks for the post! Please advise how this code works as the ternary code is confusing to me:
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];
}
can i use your code for my application?
Yes you can. But you should pay us minimum $10 USD for using our script in your project.
You can pay and download the source code from here – Pay & Download
Hi how to add an image in the product???
Hi there,
The whole code work perfectly fine. But I’m trying to do shopping cart where user can insert their shipping address at ../checkout.php
Basically there will be another forms at checkout.php for user to enter their shipping details, before they place order. I’ve tried INSERT command and using forms, but I somehow could find the correct PHP code.
Would very much appreciate your help.
Regards,
Johnny
I am planning to use your code for a shopping cart.
Have you built an Admin area for this cart? If so I would be interested in getting the code.
How about connecting the cart to PayPal?
I need to gather information about the customer. Any suggestions on how to do that?
Whole concept is fantastic, but in my case i want to count total no of items at the time of checkout . I am unable to do because i am at the learning phase. So sir kindly help me out how to count total no of product at the end.
Use the following line of code to get the total number of products on the checkout page.
Really Thanks to post this valuable code and supports
God Bless You.. 🙂
Hi,
Can you please show how to add “coupon discount” on total sales?