Table of Contents
Introduction
Let’s learn how to develop shopping cart using PHP and MySQL, in this tutorial I am going to provide details steps along with source code on how we can build simple and best shopping cart in 10 minutes.
We all know shopping cart is used to collect items at one place to submit the purchase request, so here our goal is to learn how you can list, collect and list them again into the shopping cart to purchase.
The scope of this tutorial will be to create a project with product list page along with list of products and add to cart button and shopping cart page which is going to have all necessary shopping cart features, if you want to become expert in php this is very convenient example for you to learn PHP, there are several aspect of it you will learn session management, arrays also database connectivity, fetching the records from database and using Class and object to perform certain operations.
My goal is to not only teach coding but teach secure coding, in my tutorials you will always find the best practiced which can helpful to use in development world, in this tutorial you will get example of how you can reduce coding complexity and make it simple using class and object, as a programmer you should always think of making code simple.
You can also checkout the demo before going to read complete tutorial, so that you can get complete idea on what your going to learn:
Shopping Cart Application DemoOkay so let’s begin to start on creating php mysql shopping cart demo project.
I assume that you have your system ready for php development, so go ahead create new project folder into web server root directory, ex. “php-mysql-shopping-cart”.
Get Complete Source CodeStep 1: Create and Seed Database:
We are going to need database for this demo, go ahead and create new database into mysql and use following sql script to create new table:
CREATE TABLE `products` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`description` text,
`price` float NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Now will need to insert few dummy records into the products table so that we can use those while developing shopping cart, click below link to download dummy data after downloading the below file import it into your newly created database.
[wpdm_package id=’1604′]Step 2: Build Product List Page:
The product page will have features like listing all products from the database along with add to cart button, add to cart button will redirect us to shopping cart page and respectively the product will be added to the cart so lest focus on product list page first.
Please take note we will be using bootstrap 4 for front end designing, now open your project folder into your favourite code editor and create project structure as showing below, I mean create all required files and folders as showing into below screen:
After creating file and folders open database_connection.php file and add following database connection script:
database_connection.php:
Make sure to change database connection variables values according to your database connection settings.
<?php
/**
* Tutorial: PHP MySQL Shopping Cart
*
* File: Database Configuration
*/
// database Connection variables
define('HOST', 'localhost'); // Database host name ex. localhost
define('USER', 'root'); // Database user. ex. root
define('PASSWORD', ''); // Database user password (if password is not set for given user then keep it empty )
define('DATABASE', 'YOUR-DATABASE-NAME'); // Database name
function DB()
{
$con = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
return $con;
}
?>
Next open library.php file and add following script:
library.php:
This file actually our application library, as you can see it has Shopping Cart class which is going to handle all backend operation such as getting products from the database, adding new product into the shopping cart and removing existing product from the shopping cart.
Currently Shopping cart class has “getProductions()” method only will go step by step and then will add further required method into the same class.
<?php
// load database connection script
require __DIR__ . '/database_connection.php';
/*
* Tutorial: PHP MySQL Shopping cart
*
* Page: Application library
* */
class ShopingCart
{
protected $db;
function __construct()
{
$this->db = DB();
}
/**
* get products list
*
* @return array
*/
public function getProducts()
{
$query = "SELECT * FROM `products`";
if (!$result = mysqli_query($this->db, $query)) {
exit(mysqli_error($this->db));
}
$data = [];
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
return $data;
}
}
?>
Also don’t forget to focus on how we are using database connection function into the shopping cart class.
Next open up index.php file and add following script, it has all necessary for product listing. if you see file carefully from start to end you will see how we are using our application library to get products from the database and how we are listing product on page.
<?php
// Start Session
session_start();
// Application library ( with ShopingCart class )
require __DIR__ . '/lib/library.php';
$app = new ShopingCart();
$products = $app->getProducts();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Product List</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<?php include("partials/menu.php"); ?>
<div class="row">
<div class="col-md-12">
<?php
if(count($products) > 0)
{
foreach ($products as $product) {
echo ' <div class="card mb-3">
<h5 class="card-header">
'. $product['title'] . '
</h5>
<div class="card-body">
<p class="card-text">
' . $product['description'] . '
</p>
<h4>Price: $ ' . $product['price'] . '</h4>
<div class="float-right">
<form method="post" action="cart.php" class="form-inline">
<input type="hidden" value="' . $product['id'] . '" name="product_id">
<input type="hidden" value="add_to_cart" name="add_to_cart">
<button type="submit" class="btn btn-primary">Add to Cart</button>
</form>
</div>
</div>
</div>';
}
}
?>
</div>
</div>
</div>
<?php include("partials/scripts.php"); ?>
</body>
</html>
Before going to run this page will have update our partial pages which is menu.php and scripts.php, keep in mind it is always good to separate the code to re use into the multiple location it makes code very clean and readable as well as easy to update from one place and it reflects at all the places, in this case we are going to reuse menu.php and scripts.php into cart.php page as well also similarly database connection.php and library.php file is being used.
Well lets open menu.php file into the code editor and add following menu script:
menu.php:
<nav class="navbar navbar-expand-lg navbar-light bg-light mb-4 shadow-sm rounded">
<a class="navbar-brand" href="#">PHP MySQL Shopping Cart Demo</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="index.php">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.php">My Shopping Cart</a>
</li>
</div>
</nav>
Next open up script.php:
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
Execute product list Page:
So far we are done creating product list page we should test whether it is working or not, go ahead and run your project if your coding along with me, after execute the page your should see output as showing into the below screen:
Step 3: Build Shopping Cart:
Shopping cart will have list of product along with it’s price, quantity and total amount of shopping cart along with delete button to remove any product from the shopping cart, so let’s begin go ahed and open up cart.php page and add following script:
Focus on script it’s incredibly simple to understand, start from the first section of php script we have imported application library which is going to feature all our backend operations, will update that into next step, now if you look at the further page you will see we have combination of php and html which completes the listing and all other features.
<?php
// Start Session
session_start();
// Application library ( with ShopingCart class )
require __DIR__ . '/lib/library.php';
$app = new ShopingCart();
if(isset($_POST['add_to_cart']))
{
$app->addToCart($_POST['product_id']);
}
if (isset($_GET['id_to_remove']) && isset($_GET['id_to_remove']) != '') {
$app->removeProductFromCart($_GET['id_to_remove']);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cart</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<?php include("partials/menu.php"); ?>
<div class="card">
<h5 class="card-header">My Cart</h5>
<div class="card-body">
<?php
if(isset($_SESSION['shopping_cart']) && count($_SESSION['shopping_cart']) > 0)
{
$products = $_SESSION['shopping_cart'];
echo '
<table class="table table-hover table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
<th scope="col" width="100">Action</th>
</tr>
</thead>';
$item_number = 1;
$total = 0;
foreach ($products as $product) {
echo '
<tbody>
<tr>
<th scope="row">'. $item_number .'</th>
<td>' . $product['title'] . '</td>
<td>'.$product['quantity'].'</td>
<td>$ '. $product['price']. '</td>
<td>
<a href="cart.php?id_to_remove=' . $item_number . '" class="btn btn-danger btn-sm">X</a>
</td>
</tr>
</tbody>
';
$total += ($product['price'] * $product['quantity']);
$item_number++;
}
echo '
<tr>
<th colspan="4" align="right">
Total:
</th>
<td>
$ '. $total .'
</td>
</tr>
</table>';
}
else {
echo '<div class="alert alert-primary" role="alert">
Shopping cart is empty, visit <a href="index.php" class="alert-link">products</a> page to add product into shopping cart.
</div>';
}
?>
</div>
<div class="card-footer">
<button class="btn btn-primary float-right">Proceed To Checkout</button>
</div>
</div>
</div>
<?php include("partials/scripts.php"); ?>
</body>
</html>
Update Application Library:
As you have we have called two functions into the above cart.php file those actually not exists into the library.php file, will have to add those so go ahead and open up library.php and add following functions into shopping cart class after getProducts function:
/**
* get given product details
*
* @param [integer] $id
* @return array
*/
public function getProductDetails($id)
{
$id = mysqli_real_escape_string($this->db, $id);
$query = "SELECT * FROM `products` WHERE `id` = '$id'";
if (!$result = mysqli_query($this->db, $query)) {
exit(mysqli_error($this->db));
}
$data = [];
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data['id'] = $row['id'];
$data['title'] = $row['title'];
$data['price'] = $row['price'];
$data['quantity'] = 1;
}
}
return $data;
}
/**
* Add new product into the cart
*
* @param [integer] $id
* @return void
*/
public function addToCart($id)
{
$product = $this->getProductDetails($id);
$isFound = false;
$i = 0;
if (!isset($_SESSION['shopping_cart']) || count($_SESSION['shopping_cart']) < 1)
{
$_SESSION['shopping_cart'] = array(0 => $product);
} else {
foreach ($_SESSION['shopping_cart'] as $item) {
$i++;
foreach ($item as $key => $value) {
if ($key == "id" && $value == $id) {
array_splice($_SESSION['shopping_cart'], $i - 1, 1, array([
'id' => $item['id'],
'title' => $item['title'],
'price' => $item['price'],
'quantity' => $item['quantity'] + 1,
]));
$isFound = true;
}
}
}
if ($isFound == false) {
array_push($_SESSION['shopping_cart'], $product);
}
}
}
/**
* remove existing product from the cart
*
* @param [integer] $id
* @return void
*/
public function removeProductFromCart($id)
{
unset($_SESSION['shopping_cart'][$id - 1]);
}
Note – Make sure to add above functions into the scope of ShoppingCart Class.
Test Complete Application:
Now we are almost done on creating shopping cart, let’s test how it actually works:
Go ahead open your project and click on add to cart button on any product listed, you should be redirected to the cart.php page along with shopping cart begin generated, I have added the screen below for your reference, the shopping cart should look like this:
We are done, if you want to learn next step of this application flow that is the payment process after clicking on proceed to checkout button, then you can check my one of best tutorial which will teach you how you can embed payment gateway into your application using php, follow the link below:
PayPal JavaScript Express checkout Integration in PHP MySQL
I paid I can not load this Package Build efficient PHP MySQL Shopping Cart Application
What’s the issue?
Build-efficient-PHP-MySQL-Shopping-Cart-Application.zip this error dowload
Try downloading again. let me know if you still get same issue will send you a brand new source code file.
I try to load again. Can not download
just sent you an email along with the source code attached.
hello.The delete option not deleting effectively.Kindly help..
great thanks for it