Home / PHP /

PHP Code – Shopping Cart System Tutorial using SESSIONS

php-shopping-cart-tutorial-using-sessions

If you want to build your own online shopping cart from scratch, we have good news for you! This post can help you get it done because we will build a simple shopping cart script today. We will use PHP, MySQL and PHP sessions to complete this task.

A lot of people use a ready-made software for this. But for coders like us, it is important to know how it was done so that we can create more features like making the system more secured, add some unique functionality, etc.

Just to make things more clear, the source codes in this tutorial is NOT for you if:

1. You are an already an expert in PHP & MySQL programming.
2. You have a lot of time to code a shopping cart system from scratch.
3. You are not really interested in learning PHP & MySQL programming.

But, this SOURCE CODE is FOR YOU if:

1. You want to SAVE huge amount of development time.
2. You want to develop your own shopping cart store from scratch.
3. You are determined to learn how to make a web application in PHP & MySQL (basic to advanced level)

So, let’s start off the LEVEL 1 source code. Our simple system will have two pages.

1. The products page (products.php) shows your list of products retrieved from the database. For each product, it has a blue button that says “Add to cart”, it also has a cart icon.

2. The cart page (cart.php) shows the list of products the user added to his cart. For each cart item, it has a red button that says “Remove from cart” with an “x” icon.

LEVEL 1 will cover the following contents:

1.0 Code Output Demo
2.0 Files Overview
3.0 Step By Step Programming (Steps 1-10)
4.0 Enter or Update Cart Item Quantity
5.0 Download Source Code

1.0 Code Output Demo

Live demo link is provided below the video.

If you understand how the LEVEL 1 source code works, it will lead you to the LEVEL 2 source code.

Here’s another shopping cart script demo, with the update quantity and a lot more feature. The video demo is outdated, please check the live demo link or see the section 5.3 below for a full list of LEVEL 2 features.

Live demo link is provided below the video.

After the LEVEL 2, a full blown shopping cart system awaits you! The LEVEL 3 source code has the features you imagined you need. See section 5.4 below to see the full list of features the LEVEL 3 source code has.

If you want to see a live demo of the LEVEL 3 source code, go to section 5.4 below and see how you can contact me.

2.0 Files Overview of PHP Shopping Cart Tutorial

The files overview is useful for reminding ourselves which file or part of the script are we working on. Here’s an overview of the files used in this tutorial.

files and folders for php shopping cart tutorial with cookies

Let me explain what is the use of each files and folders above.

3.1 config is a folder that contains another file called db_connect.php which is the file used to connect to the MySQL database for retrieving product information.

3.2 add_to_cart.php is executed when the user clicks on the “add to cart” button. It processes the product data by adding it to the SESSION array variable to make it a cart item.

3.3 cart.php is where the cart items are read and displayed to the user. We retrieve the items from the SESSION array variable and loop through it to be displayed on an HTML table.

3.4 layout_foot.php is used as a closing HTML wrapper, and is included at the end of cart.php and products.php because it closes the tags started by layout_head.php, it also contains any JavaScript source and jQuery codes used in this script.

3.5 layout_head.php is used as an opening HTML page wrapper. It is included at the beginning of cart.php and products.php because it contains the opening HTML tag, head tags, title tags and any CSS resource used.

3.6 navigation.php contains the links to products.php and cart.php pages that the user can click. The cart item count is also shown here, beside the “Cart” link.

3.7 products.php displays all the products retrieve from the database. We are using PDO extension to connect and retrieve data from the MySQL database.

3.8 remove_from_cart.php is executed when the user clicks on the “Remove from cart” button. It removes the product item from the SESSION array variable.

Important note: This source code focuses on using PHP sessions for storing shopping cart items, the “checkout” is not in its scope.

3.0 Step By Step Programming

Now here’s the fun part.

Step 1: In your PhpMyAdmin, create a database and run the following SQL queries to create the sample tables.

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `price` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `price`) VALUES
(1, 'LG P880 4X HD', 336),
(2, 'Google Nexus 4', 299),
(3, 'Samsung Galaxy S4', 600);

Step 2: In your chosen root directory, create a folder named config.

Step 3: Inside that config folder, create a file named db_connect.php, and put the following code inside it, just change to database credentials to your own.

<?php
$host = "your_host";
$db_name = "your_database_name";
$username = "your_database_username";
$password = "your_database_password";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

//to handle connection error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
?>

Step 4: Create a file called products.php, we will retrieve the products using the code below.

<?php
session_start();

$page_title="Products";
include 'layout_head.php';

// to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "1";
$name = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='added'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> was added to your cart!";
	echo "</div>";
}

if($action=='exists'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> already exists in your cart!";
	echo "</div>";
}

$query = "SELECT id, name, price FROM products ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();

$num = $stmt->rowCount();

if($num>0){

	//start table
	echo "<table class='table table-hover table-responsive table-bordered'>";

        // our table heading
        echo "<tr>";
            echo "<th class='textAlignLeft'>Product Name</th>";
			echo "<th>Price (USD)</th>";
			echo "<th>Action</th>";
        echo "</tr>";

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);

            //creating new table row per record
            echo "<tr>";
                echo "<td>";
					echo "<div class='product-id' style='display:none;'>{$id}</div>";
					echo "<div class='product-name'>{$name}</div>";
				echo "</td>";
				echo "<td>&#36;{$price}</td>";
				echo "<td>";
					echo "<a href='add_to_cart.php?id={$id}&name={$name}' class='btn btn-primary'>";
						echo "<span class='glyphicon glyphicon-shopping-cart'></span> Add to cart";
					echo "</a>";
				echo "</td>";
            echo "</tr>";
        }

    echo "</table>";
}

// tell the user if there's no products in the database
else{
    echo "No products found.";
}

include 'layout_foot.php';
?>

Step 5: products.php on step 4 above will not actually work without the layout_head.php and layout_foot.php, so first, we’ll create the layout_head.php with the following code:

<?php
// connect to database
include 'config/db_connect.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?> - LIVE DEMO</title>

    <!-- Bootstrap -->
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

    <!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
    <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>
<body>

	<?php include 'navigation.php'; ?>

    <!-- container -->
    <div class="container">

        <div class="page-header">
            <h1><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?></h1>
        </div>

Step 6: layout_head.php includes another PHP file called navigation.php. We’ll create the navigation.php file and put the following code.

<!-- navbar -->
<div class="navbar navbar-default navbar-static-top" role="navigation">
	<div class="container">

		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
			<span class="sr-only">Toggle navigation</span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="products.php">Your Site</a>
		</div>

		<div class="navbar-collapse collapse">
			<ul class="nav navbar-nav">
				<li <?php echo $page_title=="Products" ? "class='active'" : ""; ?> >
					<a href="products.php">Products</a>
				</li>
				<li <?php echo $page_title=="Cart" ? "class='active'" : ""; ?> >
					<a href="cart.php">
						<?php
						// count products in cart
						$cart_count=count($_SESSION['cart_items']);
						?>
						Cart <span class="badge" id="comparison-count"><?php echo $cart_count; ?></span>
					</a>
				</li>
			</ul>
		</div><!--/.nav-collapse -->

	</div>
</div>
<!-- /navbar -->

Step 7: Now we’ll create the layout_foot.php file with the code below.

	</div>
	<!-- /container -->

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

</body>
</html>

Step 8: products.php has links to the add_to_cart.php file. We’ll create that add_to_cart.php file and put the code below.

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart_items'])){
	$_SESSION['cart_items'] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart_items'])){
	// redirect to product list and tell the user it was added to cart
	header('Location: products.php?action=exists&id' . $id . '&name=' . $name);
}

// else, add the item to the array
else{
	$_SESSION['cart_items'][$id]=$name;

	// redirect to product list and tell the user it was added to cart
	header('Location: products.php?action=added&id' . $id . '&name=' . $name);
}
?>

Step 9: Now if the products were able to be added on the cart, we’ll have to view it using cart.php. We’ll create that cart.php file with the following codes.

<?php
session_start();

$page_title="Cart";
include 'layout_head.php';

$action = isset($_GET['action']) ? $_GET['action'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";

if($action=='removed'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> was removed from your cart!";
	echo "</div>";
}

else if($action=='quantity_updated'){
	echo "<div class='alert alert-info'>";
		echo "<strong>{$name}</strong> quantity was updated!";
	echo "</div>";
}

if(count($_SESSION['cart_items'])>0){

	// get the product ids
	$ids = "";
	foreach($_SESSION['cart_items'] as $id=>$value){
		$ids = $ids . $id . ",";
	}

	// remove the last comma
	$ids = rtrim($ids, ',');

	//start table
	echo "<table class='table table-hover table-responsive table-bordered'>";

        // our table heading
        echo "<tr>";
            echo "<th class='textAlignLeft'>Product Name</th>";
            echo "<th>Price (USD)</th>";
			echo "<th>Action</th>";
        echo "</tr>";

		$query = "SELECT id, name, price FROM products WHERE id IN ({$ids}) ORDER BY name";

		$stmt = $con->prepare( $query );
		$stmt->execute();

		$total_price=0;
		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);

			echo "<tr>";
				echo "<td>{$name}</td>";
				echo "<td>&#36;{$price}</td>";
				echo "<td>";
					echo "<a href='remove_from_cart.php?id={$id}&name={$name}' class='btn btn-danger'>";
						echo "<span class='glyphicon glyphicon-remove'></span> Remove from cart";
					echo "</a>";
				echo "</td>";
            echo "</tr>";

			$total_price+=$price;
		}

		echo "<tr>";
				echo "<td><b>Total</b></td>";
				echo "<td>&#36;{$total_price}</td>";
				echo "<td>";
					echo "<a href='#' class='btn btn-success'>";
						echo "<span class='glyphicon glyphicon-shopping-cart'></span> Checkout";
					echo "</a>";
				echo "</td>";
            echo "</tr>";

	echo "</table>";
}

else{
	echo "<div class='alert alert-danger'>";
		echo "<strong>No products found</strong> in your cart!";
	echo "</div>";
}

include 'layout_foot.php';
?>

Step 10: cart.php links to a file called remove_from_cart.php to remove an item from the cart. We’ll create remove_from_cart.php with the codes below.

<?php
session_start();

// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";

// remove the item from the array
unset($_SESSION['cart_items'][$id]);

// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=removed&id=' . $id . '&name=' . $name);
?>

4.0 Enter or Update Cart Item Quantity

The tutorial above only allows you to add, remove and compute the total price of items in the cart. It’s already very useful because the code shows you how to create, read, update and delete data in web cookies.

But what if your users want to enter or update the quantity of items in the cart? Is it possible using cookies? The good news is yes, it can be done. I will give you a basic idea on how I did it, see 4.1 to 4.3 below.

I did not include it in the code above because the simplicity of the tutorial will gone. I want it to be comprehensible even for beginners.

4.1 Add a new column named “Quantity” in products.php and cart.php. The word “Quantity” will be the column header and for the rest of the table row, it will be input or text boxes where the user can enter the product quantity before clicking the “Add to cart” or “Update cart” button.

4.2 On products.php, the “Add to cart” button will not be a direct link to add_to_cart.php file. It will be a button that will execute a jQuery code because it has to get the quantity entered by the user.

4.3 On cart.php, there will be an “Update cart” button beside the quantity textbox. Clicking it will run a jQuery script that gets the new quantity entered by the user and saves the changes with the help of a new file called “update_quantity.php”.

After doing my advice above, your output should look like this: LIVE DEMO

It looks simple to do, right? You can understand it more if you will see the complete source code. Please download it below so that you will get exactly what I mean and how I did it.

5.0 Source Code Download

5.1 Getting The Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:
✔ Value or skill upgrade it can bring you, or
✔ Income you can get from your website project or business.
✔ For a limited time, I will give you the source code for a low price.

DOWNLOAD THE SOURCE CODE by clicking the BUY button below.

5.2 Download LEVEL 1 Source Code

The LEVEL 1 source code is the complete source code of our step by step tutorial above. But if you need more features, refer to section 5.3 or section 5.4 and get that code.

5.3 Download LEVEL 2 Source Code

Download the LEVEL 2 Source code, it has more features such as:

FEATURES LEVEL 2
You can get all the PHP files. Yes
Working add to cart with quantity text box and button. Yes
Working update quantity text box and button. Yes
Auto-disable of already added product Yes
Pagination on products list page. Yes
Search product feature. Yes
Search result with pagination. Yes
product page with quantity and add to cart button too Yes
Shows product category. Yes
One click empty cart button. Yes
Validation on ‘add to cart’ and ‘update quantity’, it is required and must be a number. Yes
Validation on search text box, you cannot search if it is empty. Yes
Well formatted money value. Yes
Show products by category Coming Soon!
Free code updates. Yes
Free email support from me as well. Yes

Download the source code by clicking the BUY button below.

5.4 Download LEVEL 3 Source Code

The LEVEL 3 source code has the following features and benefits.

FEATURES Access Level LEVEL 3
USER MANAGEMENT
Create user Admin Yes
Read user Admin Yes
Update user Admin Yes
Delete user Admin Yes
Search user Admin Yes
Users list pagination Admin Yes
View customer order history Admin Yes
First admin cannot be deleted Admin Yes
User access level Admin & Customer Yes
Interface for admin Admin Yes
Interface for customer Customer Yes
Login page Admin & Customer Yes
Sign up page Admin & Customer Yes
Hashed password stored in the database Developer Yes
Sign up email notification with validation link Developer Coming soon!
Login user with hashed password validation Admin & Customer Yes
Log out user Admin & Customer Yes
Edit profile of currently logged in user Admin & Customer Yes
Show name of currently logged in user with icon Admin & Customer Yes
PRODUCT MANAGEMENT
Create product Admin Yes
Read product Admin Yes
Update product Admin Yes
Delete product Admin Yes
Search product Admin Yes
List of product with pagination Admin & Customer Yes
View inactive products Admin Yes
View products under a product category Admin & Customer Yes
Upload product images – multiple select Admin Yes
View product images with thumbnails Admin Yes
Delete product image with X icon Admin Yes
Upload prouct PDFs – multiple select Admin Yes
List product PDF Admin Yes
Delete product PDF Admin Yes
View single product with related information Customer Yes
View single product with add to cart button Customer Yes
View single product with image slider Customer Yes
PRODUCT CATEGORY MANAGEMENT
Create product category Admin Yes
Read product category Admin Yes
Update product category Admin Yes
Delete product category Admin Yes
Search product category Admin Yes
Product category list with pagination Admin Yes
View products under a product category Admin & Customer Yes
Auto-update product category drop down in create or update product form Admin Yes
Auto-update product categories in navigation bar Admin & Customer Yes
ORDER MANAGEMENT
Make an order Customer Yes
Auto-generated unique transaction ID Customer Yes
Add to cart button (for each item) with specified quantity Customer Yes
Cart page Customer Yes
Update quantity button for each item in cart page Customer Yes
Auto-compute subtotal in cart page Customer Yes
Auto-compute grand total in cart page Customer Yes
Remove from cart button for each item in the cart Customer Yes
Empty cart button to remove all items in the cart Customer Yes
View order history of a customer Admin & Customer Yes
Checkout page Customer Yes
Show billing information automatically on check-out page Customer Yes
Edit billing information button on checkout page Customer Yes
Show payment information on checkout page Customer Yes
Payment via cash on delivery Customer Yes
Payment via bank deposit Customer Coming soon!
Payment via PayPal Customer Coming soon!
Place order page – Thank you message Customer Yes
View list of orders Admin Yes
Pagination on list of orders Admin Yes
Latest order seen at the top of the list Admin Yes
View details of an order Admin Yes
Auto-compute order totals Admin Yes
Change status of an order (pending or completed) Admin Yes
MORE REASONS TO GET IT
Boostrap user interface Admin & Customer Yes
Page title navigation with links Admin & Customer Yes
Radio button looks like a switch Admin & Customer Yes
SQL injection protection on all form fields Admin & Customer Yes
Cross site scripting (XSS) protection on all form fields Admin & Customer Yes
Icon in all create buttons Admin Yes
Icon in all edit buttons Admin Yes
Icon in all delete buttons Admin Yes
Object oriented programming source code Developer Yes
All source code files organized by folders Developer Yes
Database configuration file in config folder Developer Yes
Well explained / commented source code Developer Yes
Free source code updates / new features update Developer Yes
Free email support Developer Yes
One-time payment Developer Yes
No recurring payment Developer Yes

The LEVEL 3 source code is now available! Thanks for all the pre-orders and support! More features and enhancements will be added in the future.

I’ll keep you updated via email with the update information and download link. Download the LEVEL 3 source code by clicking the BUY button below.

Contact me if you have any questions about the code, I’ll be more than happy to help and support you!

My email is ninjazhai30@gmail.com, you can also contact me via our official Facebook page.

Thanks for your support, it keeps this website alive!

6.0 Related Source Codes

6.1PHP Shopping Cart Tutorial Using COOKIES

6.2PHP and MySQL CRUD Tutorial for Beginners

6.3PHP Object Oriented CRUD Example with Bootstrap

Notes:

For those having some issues about the $conn variable, I highly recommend learning about PHP CRUD first. It will help you a lot.

Some of you are having a little issues fixing the undefined index notice. I updated the code above and download link to help you fix it, please try it and tell us in the comments section if it works or not. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code. :)