Home PHP

PHP and MySQL Shopping Cart Tutorial – Using SESSIONS To Store Cart Data

shopping-cart-in-php-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 learn and experience how to do it. We can create more features like making the system more secured, add some unique functionality and more.

Your imagination can be the only limit.

This post will have the following contents:

1.0 Is This Code For Me?
2.0 Code Output Demo
3.0 PHP Shopping Cart Tutorial Files
4.0 Step By Step Programming (Steps 1-10)
5.0 Enter or Update Cart Item Quantity
6.0 What People Say About This Code?
7.0 Download Source Code
8.0 What’s Next?
9.0 Related Source Code
10.0 Some Notes

1.0 Is This Code For Me?

The source codes in this page is NOT for you if:

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

But, this SOURCE CODE is FOR YOU if:

  • You want to SAVE huge amount of development time.
  • You want to develop your own shopping cart system from scratch.
  • You determined to learn how to make a web application in PHP & MySQL.

But if you are an expert in PHP & MySQL programming and would like to take a look at our code, please do so! We’d love to hear your response and great insights! The comments section below is always open for anyone with questions and suggestions.

2.0 Code Output Demo

So, let’s start off with 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.

2.1 LEVEL 1 Source Code Output

Live demo link provided below the video demo.

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

2.2 LEVEL 2 Source Code Output

LEVEL 2 source code has the update quantity feature, product search, pagination and more.

The LEVEL 2 video demo below is not the latest one, please check the live demo link or see the section 7.3 below for a full list of LEVEL 2 features.

Live demo link provided below the video.

After the LEVEL 2, a shopping cart system with back-end features awaits you in the LEVEL 3 source code!

2.3 LEVEL 3 Source Code Output

LEVEL 2 will lead you to this amazing LEVEL 3 source code.

Source code outputs above are only previews and demonstrate some of the features only. Please see section 7.0 below to see the full list of features.

For now, we will study and understand how the LEVEL 1 source code works. Learn the step by step tutorial below.

3.0 PHP Shopping Cart Tutorial Files

The files overview can help us keep track of which files we are working on. Here’s the 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. It is used to connect to the MySQL database for retrieving product information.

3.2 add_to_cart.php executes 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 the page that displays the cart items. We retrieve the items from the SESSION array variable. We loop through it to form an HTML table.

3.4 layout_foot.php acts as a closing HTML wrapper. cart.php and products.php includes this file 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 acts as an opening HTML page wrapper. cart.php and products.php have this file included. It contains the opening HTML tag, head tags, title tags and any CSS resource used.

3.6 navigation.php contains the clickable links to products.php and cart.php pages. 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 executes when the user clicks on the “Remove from cart” button. It removes the product item from the SESSION array variable.

Important note:

LEVEL 1 source code focuses on using PHP sessions to store shopping cart items. The “checkout” is not in its scope. Please take a look at the LEVEL 3 source code for checkout and a lot more features.

4.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. 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 named 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: Without the layout_head.php and layout_foot.php files, products.php on step 4 above will not work . First, we’ll have to 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: Step 9: Now, if the products were 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);
?>

5.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 useful because the code shows you how to create, read, update and delete data in PHP sessions.

But what if your users want to enter or update the quantity of items in the cart? Is it possible using PHP sessions?

The answer is YES, it can do it. I will give you a basic idea on how I did it, see 5.1 to 5.3 below.

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

5.1 Add a new column named “Quantity” in products.php and cart.php. The word “Quantity” will be the column header.

For the rest of the table row, it will be input or text boxes. This is where the user can enter the product quantity before clicking the “Add to cart” or “Update cart” button.

5.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.

5.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. It will also save the changes with the help of a new file called “update_quantity.php”.

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

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.

6.0 What People Say About This Code?

I’m so glad that this code delights other people. The following are some of them from the comments section!

★★★★★ “Hey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

★★★★★ “Man, your tut’s are awesome. Im so glad ive found your blog. Big respect!” ~ Milos

★★★★★ “I bought your level-2 source code and it was so good, very big help for me. It was worth it. Thank you very much!” ~ Ashley Deanna Plata

★★★★★ “Hello, This is a great script and I have paid 6.99 for your work (it Worth it).” ~ Louis Blais

★★★★★ “Words can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

7.0 Source Code Download

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 YES
✔ Income you can get from your website project or business. YES
✔ Precious time you save. YES
✔ Expert advice you can get from us, just in case you have any questions related to the source code. YES

For a limited time, I will give you the source code for a low price. DOWNLOAD THE SOURCE CODE LEVEL you desire by clicking its the BUY button below.

7.1 Download the LEVEL 1 Source Code

FEATURE LEVEL 1
Learn to code a simple cart function Yes
List all products from MySQL database Yes
Add to cart action button Yes
Remove from cart action button Yes
Show message about a product added to cart Yes
Show message about a product removed from cart Yes
Navigation bar highlights which page is selected Yes
Cart link shows count of products added in the cart Yes
Show message if no products found in database Yes
Show message if no product found in cart Yes
Bootstrap enabled UI Yes
Cart page that lists all products added to cart Yes
Auto-compute total cost of all products added to cart Yes
PDO extension used Yes
Step by step tutorial Yes
Free code updates Yes
Free support for 6 months Yes
LEVEL 1: BUY AND
DOWNLOAD USING

* You can use your debit or credit card with PayPal.

7.2 Download the LEVEL 2 Source Code

FEATURE LEVEL 2
All features of LEVEL 1 source code YES
List all products from MySQL database YES
Pagination on products list page YES
Navigation bar has drop down of product categories YES
Highlight selected category in drop down YES
Categories are retrieved from the database YES
Show products by category YES
List products under a category with pagination YES
Search product YES
Search results with pagination YES
Search box located on upper right corner of navigation bar YES
Search box requires search term before clicking the search button YES
Add to cart action button YES
Quantity text box beside the add to cart button YES
Quantity text box required to be a number YES
Quantity text box required to have a minimum value of 1, negative value not allowed YES
Remember the page number where the user clicked the “Add to cart” button YES
Single product view YES
Add to cart text box and button in single product view YES
Quantity text box has up and down arrow for changing value YES
Remove from cart action button YES
Show message about a product added to cart YES
Disable products already added in the cart YES
Show message about a product removed from cart YES
Navigation bar highlights which page is selected YES
Cart link shows count of products added in the cart YES
Show message if no products found in database YES
Show message if no product found in cart YES
Well formatted money value YES
Check out button with cart icon YES
Bootstrap enabled UI YES
Cart page that lists all products added to cart YES
Quantity text box beside update quantity button YES
One click empty cart button YES
Auto-compute total cost of all products added to cart YES
Used PDO bindParam() to prevent SQL injection in MySQL queries YES
Used PHP htmlspecialchars() to prevent XSS attacks YES
SQL file is in the “dev” folder YES
PDO extension used YES
Free code updates YES
Free support for 6 months YES
LEVEL 2: BUY AND
DOWNLOAD USING

* You can use your debit or credit card with PayPal.

7.3 Download LEVEL 3 Source Code

FEATURE LEVEL 3
All features of LEVEL 2 source code YES
CUSTOMER
Customer Registration YES
Customer Login YES
Customer Logout YES
Checkout page YES
Login prompt in checkout page (If user not yet logged in) YES
Maintain cart items after login YES
Place order YES
User orders list page YES
Order details page YES
ADMIN
Admin Login YES
Admin Logout YES
Create product YES
Read product YES
Update product YES
Delete product YES
Search product YES
Upload product image YES
Upload product PDF YES
Rich text editor in product description YES
Product active until date with jQuery UI date picker YES
View active & inactive product YES
View products by category YES
List orders from different users YES
Search order by transaction ID YES
Require value in transaction search field YES
View order details YES
Change order status (pending or completed) YES
Create user YES
Read users YES
Update user YES
Delete user YES
Search user by email address YES
Require value in user search field YES
Paginate users list YES
MORE
Free code updates YES
Free support for 6 months YES
LEVEL 3: BUY AND
DOWNLOAD USING

* You can use your debit or credit card with PayPal.

7.4 Download PHP Shoping Cart System Source Code

Many of you requested this source code. You needed a shopping cart system with user management (merchant and customer), product management, category management, order management, security and more features based on our source codes here in codeofaninja.com. Click here to learn more.

7.5 How To Add PayPal and Credit Card Checkout?

Some of you require a PayPal checkout feature. We’ve made a source code that works for that purpose. Click here to learn more.

8.0 What’s Next?

We just learned how to code an online shopping cart from scratch using PHP SESSIONS.

But did you know that we can create the almost the same functions using another PHP mechanism called COOKIES?

If you’re excited to learn this new concept, let us go to the next tutorial: PHP Shopping Cart Tutorial Using COOKIES

9.0 Related Source Codes

The following related source code tutorials can be very useful to further improve your skills.

PHP CRUD Tutorials
1.0 CRUD with PHP & MySQL for Beginners
2.0 CRUD with PHP and AJAX
3.0 CRUD with PHP and OOP
4.0 CRUD with PHP, AJAX and OOP
5.0 CRUD with PHP and AngularJS
PHP Shopping Cart Tutorials
1.0 Shopping Cart Tutorial using SESSIONS
2.0 Shopping Cart Tutorial using COOKIES
3.0 Shopping Cart Tutorial using MySQL
PHP Web Application Source Codes
PHP Shopping Cart System
PayPal Integration In PHP
PHP Login System

10.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email mike@codeofaninja.com, or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

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

#2 Need Web Hosting?

Do you need a web host for your PHP projects? This will enable your project to be accessible online.

I can provide one for you for a very affordable price of $3 per month. I will give you access to FTP, PhpMyAdmin and other things you need for development.

Send me a message on our official Facebook page, or via my email mike@codeofaninja.com, we will set up your server and URL!

#3 Need A Coder?

If you don’t like coding but wanna make it work on your website, even with any customization, don’t worry, I'll help you with the best I can!

Just contact me by sending a message on our official Facebook page, or via my email mike@codeofaninja.com, I’m more than willing to help you!

#4 Web Resources

If you need Bootstrap website themes, Bootstrap dashboard theme, my highly recommended books and other very useful resource for developers, please visit this page.

If you love high quality, good looking, educational and inspirational pictures about programming and tech industry, you should follow us on Instagram.

#5 Thank You!

Thank you for studying our tutorial about PHP Shopping Cart Tutorial using SESSIONS!