PHP Shopping Cart Tutorial using Sessions

PHP Shopping Cart Tutorial using Sessions
PHP Shopping Cart Tutorial using Sessions

This post is about PHP Shopping Cart Tutorial using SESSIONS. Previously, we learned how to build a Shopping Cart with PHP & MySQL where we used a MySQL database to store products added to the cart. This time, we will use PHP session variables to store products added to the cart.

Final output

PHP Shopping Cart Tutorial using SESSIONS

At the end of this tutorial, you will achieve the following features.

  • Products list with pagination
  • Product page
  • Add to cart function
  • Update cart function
  • Delete product from cart function
  • Cart page
  • Checkout page
  • Thank you page

Prepare the database

Database Design

Our database name will be called “shop_cart_sessions_1“, and we will have two (2) tables. The image below is a visual representation of our database tables and how they are related.

php shopping cart tutorial database design

Create a database

Start Apache and MySQL. If you’re using XAMPP like me, you can do it using its control panel.

Once Apache and MySQL are running, open your PhpMyAdmin (http://localhost/phpmyadmin). Create a new database. Use “shop_cart_sessions_1” as database name. Click the “Create” button.

Create “products” table

In this section, we will create the “products” table (using PhpMyAdmin) on the database we just created. This table will store the product records.

Run the SQL statement using PhpMyAdmin. Click “shop_cart_sessions_1” database. Click the “SQL” tab. Copy the SQL statement below and paste it in the text area. Click the “Go” button.

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COMMENT='products that can be added to cart' AUTO_INCREMENT=41 ;

Create “categories” table

This table will hold images related to the product. Run the following SQL statement on PhpMyAdmin as well. Follow the same steps we did on the “products” table.

CREATE TABLE IF NOT EXISTS `product_images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `name` varchar(512) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='image files related to a product' AUTO_INCREMENT=105 ;

Download sample data

The products and product_images table will not fully work without the sample data and related image files. Use the following button to download the ZIP file.

Extract and import data

Once downloaded, please extract the files. Import the SQL file using PhpMyAdmin.

Put the image files in “php-shopping-cart-using-sessions-level-1/uploads/images/” directory. That directory does not exist yet. Follow the steps below to create it.

Create “php-shopping-cart-using-sessions-level-1” folder and open it. This is our project’s main folder. Create the “uploads” folder and open it. Create an “images” folder and open it. Copy and paste the images on this directory.

Database connection file

This file will be used to get establish a database connection. Create “config” folder and open it. Create “database.php” file and open it. Put the following code.

<?php
// used to get mysql database connection
class Database{
	// specify your own database credentials
	private $host = "localhost";
	private $db_name = "shop_cart_sessions_1";
	private $username = "root";
	private $password = "";
	public $conn;
	// get the database connection
	public function getConnection(){
		$this->conn = null;
		try{
			$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
		}catch(PDOException $exception){
			echo "Connection error: " . $exception->getMessage();
		}
		return $this->conn;
	}
}
?>

Output

Our PhpMyAdmin should look like the image below. A database with two tables.

We don’t have an actual program output yet because we only set up the database. Let’s continue our tutorial below to achieve more outputs.

Create the layout files

The layout files contain code that can be re-used on each web page. The look of our pages will be consistent because of these header and footer layout files.

Create header layout file

This “layout_header.php” file will be included at the beginning of the PHP files that will need it. This way, we won’t have to write the same header codes every time.

We use the Bootstrap framework to make our project look good. If you’re not yet familiar with Bootstrap, you may learn from our Bootstrap tutorial here.

Create “layout_header.php” file. Place the following code. By the way, please note that after we put a code on a file, always save your changes. You can use CTRL+S to save if you’re using Windows like me.

This code contains our session variable that will hold the products added to the cart. We put it here so we don’t need to re-initialize it on every page.

The title tags contain PHP code that will make our page title dynamic. Bootstrap CSS and our custom CSS are included inside the head tags. Our navigation bar is inside the navigation.php file, we will create this file later.

<?php
// session variable that will hold products added to cart
$_SESSION['cart']=isset($_SESSION['cart']) ? $_SESSION['cart'] : array();
?>
<!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"; ?></title>
    <!-- Latest compiled and minified Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <!-- our custom CSS -->
    <link rel="stylesheet" href="libs/css/custom.css" />
</head>
<body>
	<?php include 'navigation.php'; ?>
    <!-- container -->
    <div class="container">
        <div class="row">
        <div class="col-md-12">
            <div class="page-header">
                <h1><?php echo isset($page_title) ? $page_title : "The Code of a Ninja"; ?></h1>
            </div>
        </div>

This “layout_footer.php” will be included at the end of the PHP files that will need it. This way, we won’t have to write the same footer codes every time.

We are using jQuery and Bootstrap’s JavaScript in the footer layout file. jQuery is required by Bootstrap’s JavaScript which is needed for features like a navigation drop-down

Create a “layout_footer.php” file. Put the following code.

		</div>
		<!-- /row -->
	</div>
	<!-- /container -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- Latest compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- custom script will be here -->
</body>
</html>

Create navigation layout file

Create “navigation.php” file. Put the following code. This code will display the navigation bar with “Products” and “Cart” menu links. It will also display the number of products added to the cart.

<!-- 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">XYZ Webstore</a>
		</div>
		<div class="navbar-collapse collapse">
			<ul class="nav navbar-nav">
				<!-- highlight if $page_title has 'Products' word. -->
				<li <?php echo $page_title=="Products" ? "class='active'" : ""; ?>>
					<a href="products.php" class="dropdown-toggle">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']);
						?>
						Cart <span class="badge" id="comparison-count"><?php echo $cart_count; ?></span>
					</a>
				</li>
			</ul>
		</div><!--/.nav-collapse -->
	</div>
</div>
<!-- /navbar -->

Create custom CSS file

This custom.css file is where our custom styles are located.

  • Open “php-shopping-cart-using-sessions-level-1” folder.
  • Open “libs” folder.
  • Open “css” folder.
  • Create “custom.css” file.
  • Place the following code.
.text-align-center{ text-align:center; }
.f-w-b{ font-weight:bold; }
.display-none{ display:none; }
.w-5-pct{ width:5%; }
.w-10-pct{ width:10%; }
.w-15-pct{ width:15%; }
.w-20-pct{ width:20%; }
.w-25-pct{ width:25%; }
.w-30-pct{ width:30%; }
.w-35-pct{ width:35%; }
.w-40-pct{ width:40%; }
.w-45-pct{ width:45%; }
.w-50-pct{ width:50%; }
.w-55-pct{ width:55%; }
.w-60-pct{ width:60%; }
.w-65-pct{ width:65%; }
.w-70-pct{ width:70%; }
.w-75-pct{ width:75%; }
.w-80-pct{ width:80%; }
.w-85-pct{ width:85%; }
.w-90-pct{ width:90%; }
.w-95-pct{ width:95%; }
.w-100-pct{ width:100%; }
.m-t-0px{ margin-top:0px; }
.m-b-10px{ margin-bottom:10px; }
.m-b-20px{ margin-bottom:20px; }
.m-b-30px{ margin-bottom:30px; }
.m-b-40px{ margin-bottom:40px; }
.stock-text {
    font-weight: bold;
    color: #008a00;
}
.stock-text-red{
    font-weight:bold;
    color:#b12704;
}
.product-detail {
    font-weight: bold;
    margin: 0 0 5px 0;
}
.blueimp-gallery>.prev, .blueimp-gallery>.next{ border:none; }
.update-quantity-form {
    width: 150px;
    float: left;
    margin: 0 10px 0 0;
}
.cart-row {
    border-bottom: thin solid #f1f1f1;
    overflow: hidden;
    width: 100%;
    padding: 20px 0 20px 0;
}
.product-link{
    color:#000000;
}
.product-link:hover{
    color:#000000;
    text-decoration:none;
}
.product-img-thumb {
    margin: 0 0 10px 0;
    width: 100%;
    cursor: pointer;
}

Output

The files we created in this section is meant to be used within another PHP file. If we will try to run the files, we won’t see anything meaningful yet.

If you will run layout_header.php file, it will look like this.

The custom.css looks like this.

The navigation.php looks like this.

The footer.php is blank. Let’s continue on the next section to see something meaningful.

Display Products

Create products.php

Now we are going to start displaying products from the database. Create products.php with the following basic code.

<?php
// start session
session_start();
// set page title
$page_title="Products";
// page header html
include 'layout_header.php';
// contents will be here
// layout footer code
include 'layout_footer.php';
?>

Include PHP Classes

Put the following code after “session_start();” code of the previous section.

// connect to database
include 'config/database.php';
// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
// class instances will be here

Create “product” object file

Create “objects” folder. Inside it, create product.php file with the following code.

<?php
// 'product' object
class Product{
	// database connection and table name
	private $conn;
	private $table_name="products";
	// object properties
	public $id;
	public $name;
	public $price;
	public $description;
	public $category_id;
	public $category_name;
	public $timestamp;
	// constructor
	public function __construct($db){
		$this->conn = $db;
	}
}

Create “product image” object file

Create product_image.php file inside “objects” folder.

<?php
// 'product image' object
class ProductImage{
	// database connection and table name
	private $conn;
	private $table_name = "product_images";
	// object properties
	public $id;
	public $product_id;
	public $name;
	public $timestamp;
	// constructor
	public function __construct($db){
		$this->conn = $db;
	}
}

Connect to the database

Open products.php file. Replace // class instances will be here comment with the following code.

// get database connection
$database = new Database();
$db = $database->getConnection();
// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);

Initialize action and pagination

Put the following code after the code on the previous section.

// to prevent undefined index notice
$action = isset($_GET['action']) ? $_GET['action'] : "";
// for pagination purposes
$page = isset($_GET['page']) ? $_GET['page'] : 1; // page is the current page, if there's nothing set, default is page 1
$records_per_page = 6; // set records or rows of data per page
$from_record_num = ($records_per_page * $page) - $records_per_page; // calculate for the query LIMIT clause

Display messages based on action

We’ll display messages basedon given action.

Put the following code after include ‘layout_header.php‘; code.

echo "<div class='col-md-12'>";
	if($action=='added'){
		echo "<div class='alert alert-info'>";
			echo "Product was added to your cart!";
		echo "</div>";
	}
	if($action=='exists'){
		echo "<div class='alert alert-info'>";
			echo "Product already exists in your cart!";
		echo "</div>";
	}
echo "</div>";

Request data from the database

Request data from the database. Put the following code after the code on the previous section.

// read all products in the database
$stmt=$product->read($from_record_num, $records_per_page);
// count number of retrieved products
$num = $stmt->rowCount();
// if products retrieved were more than zero
if($num>0){
	// needed for paging
	$page_url="products.php?";
	$total_rows=$product->count();
	// show products
	include_once "read_products_template.php";
}
// tell the user if there's no products in the database
else{
	echo "<div class='col-md-12'>";
    	echo "<div class='alert alert-danger'>No products found.</div>";
	echo "</div>";
}

Add “read” and “count” methods

The previous section will not work without the following code inside “objects/product.php” object file.

// read all products
function read($from_record_num, $records_per_page){
	// select all products query
	$query = "SELECT
				id, name, description, price
			FROM
				" . $this->table_name . "
			ORDER BY
				created DESC
			LIMIT
				?, ?";
	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	// bind limit clause variables
	$stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
	$stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);
	// execute query
	$stmt->execute();
	// return values
	return $stmt;
}
// used for paging products
public function count(){
	// query to count all product records
	$query = "SELECT count(*) FROM " . $this->table_name;
	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	// execute query
	$stmt->execute();
	// get row value
	$rows = $stmt->fetch(PDO::FETCH_NUM);
	// return count
	return $rows[0];
}

Template to display products

The products.php won’t work without “read_products_template.php“, so create that file and put the following code.

<?php
if(!isset($_SESSION['cart'])){
	$_SESSION['cart']=array();
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	extract($row);
	// creating box
	echo "<div class='col-md-4 m-b-20px'>";
		// product id for javascript access
		echo "<div class='product-id display-none'>{$id}</div>";
		echo "<a href='product.php?id={$id}' class='product-link'>";
			// select and show first product image
			$product_image->product_id=$id;
			$stmt_product_image=$product_image->readFirst();
			while ($row_product_image = $stmt_product_image->fetch(PDO::FETCH_ASSOC)){
				echo "<div class='m-b-10px'>";
					echo "<img src='uploads/images/{$row_product_image['name']}' class='w-100-pct' />";
				echo "</div>";
			}
			// product name
			echo "<div class='product-name m-b-10px'>{$name}</div>";
		echo "</a>";
		// add to cart button
		echo "<div class='m-b-10px'>";
			if(array_key_exists($id, $_SESSION['cart'])){
				echo "<a href='cart.php' class='btn btn-success w-100-pct'>";
					echo "Update Cart";
				echo "</a>";
			}else{
				echo "<a href='add_to_cart.php?id={$id}&page={$page}' class='btn btn-primary w-100-pct'>Add to Cart</a>";
			}
		echo "</div>";
	echo "</div>";
}
include_once "paging.php";
?>

Add “readFirst()” method

Add “readFirst()” method in “objects/product_image.php” file. The previous section will not work without it.

// read the first product image related to a product
function readFirst(){
	// select query
	$query = "SELECT id, product_id, name
			FROM " . $this->table_name . "
			WHERE product_id = ?
			ORDER BY name DESC
			LIMIT 0, 1";
	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	// sanitize
	$this->id=htmlspecialchars(strip_tags($this->id));
	// bind prodcut id variable
	$stmt->bindParam(1, $this->product_id);
	// execute query
	$stmt->execute();
	// return values
	return $stmt;
}

Make “add to cart” button work

Open layout_footer.php file. Replace <!-- custom script will be here --> comment with the following code.

<script>
$(document).ready(function(){
	// add to cart button listener
	$('.add-to-cart-form').on('submit', function(){
		// info is in the table / single product layout
		var id = $(this).find('.product-id').text();
		var quantity = $(this).find('.cart-quantity').val();
		// redirect to add_to_cart.php, with parameter values to process the request
		window.location.href = "add_to_cart.php?id=" + id + "&quantity=" + quantity;
		return false;
	});
});
</script>

Create pagination file

The read_products_template.php file won’t work without the paging.php file. Create paging.php with the following code.

<?php
echo "<div class='col-md-12'>";
    echo "<ul class='pagination m-b-20px m-t-0px'>";
    // button for first page
    if($page>1){
        echo "<li><a href='{$page_url}' title='Go to the first page.'>";
            echo "First Page";
        echo "</a></li>";
    }
    $total_pages = ceil($total_rows / $records_per_page);
    // range of links to show
    $range = 2;
    // display links to 'range of pages' around 'current page'
    $initial_num = $page - $range;
    $condition_limit_num = ($page + $range)  + 1;
    for ($x=$initial_num; $x<$condition_limit_num; $x++) {
        // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
        if (($x > 0) && ($x <= $total_pages)) {
            // current page
            if ($x == $page) {
                echo "<li class='active'><a href=\"#\">$x <span class=\"sr-only\">(current)</span></a></li>";
            }
            // not current page
            else {
                echo "<li><a href='{$page_url}page=$x'>$x</a></li>";
            }
        }
    }
    // button for last page
    if($page<$total_pages){
        echo "<li>";
            echo "<a href='" . $page_url . "page={$total_pages}' title='Last page is {$total_pages}.'>";
                echo "Last Page";
            echo "</a>";
        echo "</li>";
    }
    echo "</ul>";
echo "</div>";
?>

Output

Run your products.php file on the browser http://localhost/php-shopping-cart-using-sessions-level-1/products.php. You should see an output like the image below.

How to add to cart?

Create add_to_cart.php

Create add_to_cart.php file because when ‘Add to cart’ button was clicked, that file with the following code inside will be executed.

<?php
// start session
session_start();
// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : 1;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;
// add new item on array
$cart_item=array(
	'quantity'=>$quantity
);
/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(!isset($_SESSION['cart'])){
	$_SESSION['cart'] = array();
}
// check if the item is in the array, if it is, do not add
if(array_key_exists($id, $_SESSION['cart'])){
	// redirect to product list and tell the user it was added to cart
	header('Location: products.php?action=exists&id=' . $id . '&page=' . $page);
}
// else, add the item to the array
else{
	$_SESSION['cart'][$id]=$cart_item;
	// redirect to product list and tell the user it was added to cart
	header('Location: products.php?action=added&page=' . $page);
}
?>

Create cart.php

Create cart.php with the following basic code.

<?php
// start session
session_start();
// connect to database
include 'config/database.php';
// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
// get database connection
$database = new Database();
$db = $database->getConnection();
// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
// set page title
$page_title="Cart";
// include page header html
include 'layout_header.php';
// contents will be here
// layout footer
include 'layout_footer.php';
?>

Display message based on action

We’ll display message on cart.php based on given action.

Put the following code after include ‘layout_header.php‘; of the previous section.

$action = isset($_GET['action']) ? $_GET['action'] : "";
echo "<div class='col-md-12'>";
	if($action=='removed'){
		echo "<div class='alert alert-info'>";
			echo "Product was removed from your cart!";
		echo "</div>";
	}
	else if($action=='quantity_updated'){
		echo "<div class='alert alert-info'>";
			echo "Product quantity was updated!";
		echo "</div>";
	}
echo "</div>";

Display cart items

Put the following code after the code of the previous section.

if(count($_SESSION['cart'])>0){
	// get the product ids
	$ids = array();
	foreach($_SESSION['cart'] as $id=>$value){
		array_push($ids, $id);
	}
	$stmt=$product->readByIds($ids);
	$total=0;
	$item_count=0;
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
		$quantity=$_SESSION['cart'][$id]['quantity'];
		$sub_total=$price*$quantity;
		// =================
		echo "<div class='cart-row'>";
			echo "<div class='col-md-8'>";
				echo "<div class='product-name m-b-10px'><h4>{$name}</h4></div>";
				// update quantity
				echo "<form class='update-quantity-form'>";
					echo "<div class='product-id' style='display:none;'>{$id}</div>";
					echo "<div class='input-group'>";
						echo "<input type='number' name='quantity' value='{$quantity}' class='form-control cart-quantity' min='1' />";
							echo "<span class='input-group-btn'>";
								echo "<button class='btn btn-default update-quantity' type='submit'>Update</button>";
							echo "</span>";
					echo "</div>";
				echo "</form>";
				// delete from cart
				echo "<a href='remove_from_cart.php?id={$id}' class='btn btn-default'>";
					echo "Delete";
				echo "</a>";
			echo "</div>";
			echo "<div class='col-md-4'>";
				echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
			echo "</div>";
		echo "</div>";
		// =================
		$item_count += $quantity;
		$total+=$sub_total;
	}
	echo "<div class='col-md-8'></div>";
	echo "<div class='col-md-4'>";
		echo "<div class='cart-row'>";
			echo "<h4 class='m-b-10px'>Total ({$item_count} items)</h4>";
			echo "<h4>$" . number_format($total, 2, '.', ',') . "</h4>";
	        echo "<a href='checkout.php' class='btn btn-success m-b-10px'>";
	        	echo "<span class='glyphicon glyphicon-shopping-cart'></span> Proceed to Checkout";
	        echo "</a>";
		echo "</div>";
	echo "</div>";
}
// no products were added to cart
else{
	echo "<div class='col-md-12'>";
		echo "<div class='alert alert-danger'>";
			echo "No products found in your cart!";
		echo "</div>";
	echo "</div>";
}

Read products by IDs

The previous section will not work without the following “readByIds()” method inside “objects/product.php” file.

// read all product based on product ids included in the $ids variable
// reference http://stackoverflow.com/a/10722827/827418
public function readByIds($ids){
	$ids_arr = str_repeat('?,', count($ids) - 1) . '?';
	// query to select products
	$query = "SELECT id, name, price FROM " . $this->table_name . " WHERE id IN ({$ids_arr}) ORDER BY name";
	// prepare query statement
	$stmt = $this->conn->prepare($query);
	// execute query
	$stmt->execute($ids);
	// return values from database
	return $stmt;
}

Output

When user click the “Add to cart” button.

Go to the cart page by clicking the “Cart” option on the navigation bar.

How to update cart?

Update cart quantity with JavaScript

We have the ‘update’ button on cart.php file. When that button was clicked, a javascript code is triggered.

Place the following code inside $(document).ready(function(){ of layout_footer.php file.

// update quantity button listener
$('.update-quantity-form').on('submit', function(){
	// get basic information for updating the cart
	var id = $(this).find('.product-id').text();
	var quantity = $(this).find('.cart-quantity').val();
	// redirect to update_quantity.php, with parameter values to process the request
	window.location.href = "update_quantity.php?id=" + id + "&quantity=" + quantity;
	return false;
});

PHP script to update cart

The previous section will not work without this file.

Create update_quantity.php file. Place the following code and save it.

<?php
session_start();
// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : 1;
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;
// remove the item from the array
unset($_SESSION['cart'][$id]);
// add the item with updated quantity
$_SESSION['cart'][$id]=array(
	'quantity'=>$quantity
);
// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=quantity_updated&id=' . $id);
?>

How to remove product on cart?

We have the ‘remove’ button on cart.php file. When that button was clicked, it will trigger remove_from_cart.php file.

Create remove_from_cart.php file. Place the following code and save it.

<?php
// start session
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'][$id]);
// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=removed&id=' . $id);
?>

Create the checkout page

The checkout page looks like the cart page but the items cannot be updated or removed. It just like the summary of orders. Create checkout.php with the following code.

<?php
// start session
session_start();
// connect to database
include 'config/database.php';
// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
// get database connection
$database = new Database();
$db = $database->getConnection();
// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
// set page title
$page_title="Checkout";
// include page header html
include 'layout_header.php';
if(count($_SESSION['cart'])>0){
	// get the product ids
	$ids = array();
	foreach($_SESSION['cart'] as $id=>$value){
		array_push($ids, $id);
	}
	$stmt=$product->readByIds($ids);
	$total=0;
	$item_count=0;
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
		$quantity=$_SESSION['cart'][$id]['quantity'];
		$sub_total=$price*$quantity;
		//echo "<div class='product-id' style='display:none;'>{$id}</div>";
		//echo "<div class='product-name'>{$name}</div>";
		// =================
		echo "<div class='cart-row'>";
			echo "<div class='col-md-8'>";
				echo "<div class='product-name m-b-10px'><h4>{$name}</h4></div>";
                echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>{$quantity} item</div>";
			echo "</div>";
			echo "<div class='col-md-4'>";
				echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
			echo "</div>";
		echo "</div>";
		// =================
		$item_count += $quantity;
		$total+=$sub_total;
	}
	// echo "<div class='col-md-8'></div>";
	echo "<div class='col-md-12 text-align-center'>";
		echo "<div class='cart-row'>";
            if($item_count>1){
    			echo "<h4 class='m-b-10px'>Total ({$item_count} items)</h4>";
            }else{
                echo "<h4 class='m-b-10px'>Total ({$item_count} item)</h4>";
            }
			echo "<h4>$" . number_format($total, 2, '.', ',') . "</h4>";
	        echo "<a href='place_order.php' class='btn btn-lg btn-success m-b-10px'>";
	        	echo "<span class='glyphicon glyphicon-shopping-cart'></span> Place Order";
	        echo "</a>";
		echo "</div>";
	echo "</div>";
}
else{
	echo "<div class='col-md-12'>";
		echo "<div class='alert alert-danger'>";
			echo "No products found in your cart!";
		echo "</div>";
	echo "</div>";
}
include 'layout_footer.php';
?>

Create place_order.php

We’ll use this file to show a “thank you” message and remove all items in the cart.

Create place_order.php file. Place the following code.

<?php
// start session
session_start();
// remove items from the cart
session_destroy();
// set page title
$page_title="Thank You!";
// include page header HTML
include_once 'layout_header.php';
echo "<div class='col-md-12'>";
	// tell the user order has been placed
	echo "<div class='alert alert-success'>";
		echo "<strong>Your order has been placed!</strong> Thank you very much!";
	echo "</div>";
echo "</div>";
// include page footer HTML
include_once 'layout_footer.php';
?>

Output

When user click the “Update” button in the cart page.

If user click the “Delete” button.

The checkout page.

When user click the “Place Order” button.

How to make the product page?

Create product.php

Create product.php with the following basic code.

<?php
// start session
session_start();
// include classes
include_once "config/database.php";
include_once "objects/product.php";
include_once "objects/product_image.php";
// get database connection
$database = new Database();
$db = $database->getConnection();
// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
// include page header HTML
include_once 'layout_header.php';
// content will be here
// include page footer HTML
include_once 'layout_footer.php';
?>

Read product details

Put the following code after “$product_image = new ProductImage($db);” code of the previous section.

// get ID of the product to be edited
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');
// set the id as product id property
$product->id = $id;
// to read single record product
$product->readOne();
// set page title
$page_title = $product->name;
// product thumbnail will be here

Read one product method

The previous section will not work without the “readOne()” method. Add the following method inside “objects/product.php” file.

// used when filling up the update product form
function readOne(){
	// query to select single record
	$query = "SELECT
				name, description, price
			FROM
				" . $this->table_name . "
			WHERE
				id = ?
			LIMIT
				0,1";
	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	// sanitize
	$this->id=htmlspecialchars(strip_tags($this->id));
	// bind product id value
	$stmt->bindParam(1, $this->id);
	// execute query
	$stmt->execute();
	// get row values
	$row = $stmt->fetch(PDO::FETCH_ASSOC);
	// assign retrieved row value to object properties
	$this->name = $row['name'];
	$this->description = $row['description'];
	$this->price = $row['price'];
}

Display product thumbnails

When these product thumbnails were hovered, it displayes a larger version of the image. It is Amazon-style.

Open product.php file. Replace // product thumbnail will be here comment with the following code.

// set product id
$product_image->product_id=$id;
// read all related product image
$stmt_product_image = $product_image->readByProductId();
// count all relatd product image
$num_product_image = $stmt_product_image->rowCount();
echo "<div class='col-md-1'>";
	// if count is more than zero
	if($num_product_image>0){
		// loop through all product images
		while ($row = $stmt_product_image->fetch(PDO::FETCH_ASSOC)){
			// image name and source url
			$product_image_name = $row['name'];
			$source="uploads/images/{$product_image_name}";
			echo "<img src='{$source}' class='product-img-thumb' data-img-id='{$row['id']}' />";
		}
	}else{ echo "No images."; }
echo "</div>";
// product image will be here

The previous section section will not work without the “readByProductId()” method inside “objects/product_image.php” file.

// read all product image related to a product
function readByProductId(){
	// select query
	$query = "SELECT id, product_id, name
			FROM " . $this->table_name . "
			WHERE product_id = ?
			ORDER BY name ASC";
	// prepare query statement
	$stmt = $this->conn->prepare( $query );
	// sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));
	// bind prodcut id variable
	$stmt->bindParam(1, $this->product_id);
	// execute query
	$stmt->execute();
	// return values
	return $stmt;
}

Only one product image are displayed at a time. This part displays the larger product image based on the hovered product thumbnail.

Open product.php file. Replace // product image will be here comment with the following code.

echo "<div class='col-md-4' id='product-img'>";
	// read all related product image
	$stmt_product_image = $product_image->readByProductId();
	$num_product_image = $stmt_product_image->rowCount();
	// if count is more than zero
	if($num_product_image>0){
		// loop through all product images
		$x=0;
		while ($row = $stmt_product_image->fetch(PDO::FETCH_ASSOC)){
			// image name and source url
			$product_image_name = $row['name'];
			$source="uploads/images/{$product_image_name}";
			$show_product_img=$x==0 ? "display-block" : "display-none";
			echo "<a href='{$source}' target='_blank' id='product-img-{$row['id']}' class='product-img {$show_product_img}'>";
				echo "<img src='{$source}' style='width:100%;' />";
			echo "</a>";
			$x++;
		}
	}else{ echo "No images."; }
echo "</div>";
// product details will be here

Make image hover work

Put the following jQuery code inside “$(document).ready(function(){” of layout_footer.php file.

// change product image on hover
$(document).on('mouseenter', '.product-img-thumb', function(){
	var data_img_id = $(this).attr('data-img-id');
	$('.product-img').hide();
	$('#product-img-'+data_img_id).show();
});

Display product details

This part display product price, description and category.

Open product.php file. Replace // product details will be here comment with the following code.

echo "<div class='col-md-5'>";
	echo "<div class='product-detail'>Price:</div>";
	echo "<h4 class='m-b-10px price-description'>$" . number_format($product->price, 2, '.', ',') . "</h4>";
	echo "<div class='product-detail'>Product description:</div>";
	echo "<div class='m-b-10px'>";
		// make html
		$page_description = htmlspecialchars_decode(htmlspecialchars_decode($product->description));
		// show to user
		echo $page_description;
	echo "</div>";
	echo "<div class='product-detail'>Product category:</div>";
	echo "<div class='m-b-10px'>{$product->category_name}</div>";
echo "</div>";

Render ‘Cart’ button

Now we will display ‘Add to cart’ button if the product is not yet added to cart. Else, we will display ‘update cart’ button.

Place the following code after the previous section’s code.

echo "<div class='col-md-2'>";
	// if product was already added in the cart
	if(array_key_exists($id, $_SESSION['cart'])){
		echo "<div class='m-b-10px'>This product is already in your cart.</div>";
		echo "<a href='cart.php' class='btn btn-success w-100-pct'>";
			echo "Update Cart";
		echo "</a>";
	}
	// if product was not added to the cart yet
	else{
		echo "<form class='add-to-cart-form'>";
			// product id
			echo "<div class='product-id display-none'>{$id}</div>";
			echo "<div class='m-b-10px f-w-b'>Quantity:</div>";
			echo "<input type='number' value='1' class='form-control m-b-10px cart-quantity' min='1' />";
			// enable add to cart button
			echo "<button style='width:100%;' type='submit' class='btn btn-primary add-to-cart m-b-10px'>";
				echo "<span class='glyphicon glyphicon-shopping-cart'></span> Add to cart";
			echo "</button>";
		echo "</form>";
	}
echo "</div>";

Output

When user click on any product image in products.php page, he will land to a product page that looks like the image below.


If user hovers on any of those thumbnail or small images, the big image will change as well. The “Add to cart” button is working as well.

Here’s the output when the product is already added to cart.

If user click the “Update Cart” button, he will land on the cart page where he can update the cart quantity.

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

Download source code

We highly recommend following our well-detailed, step-by-step tutorial above first. Nothing beats experience when it comes to learning. But we believe you will learn faster if you’ll see the final source code as well. We consider it as your additional guide.

Imagine the value or skill upgrade it can bring you. The additional income you can get from your work, projects, or business. The precious time you save.

List of features

FeaturesLEVEL 1 Source codeLEVEL 2 Source code
Learn to code a simple cart functionYESYES
List all products from the MySQL databaseYESYES
Pagination on the products list pageYESYES
Add to cart action buttonYESYES
Remove from the cart action buttonYESYES
Update product quantityYESYES
Checkout page, place order page & thank you pageYESYES
Amazon-style product details pageYESYES
Change image on hover of thumbnailYESYES
Show message about a product added to cartYESYES
Show message about a product removed from cartYESYES
Navigation bar highlights which page is selectedYESYES
Show number of products added to cart in the cart menuYESYES
Show message if no products found in databaseYESYES
Show message if no product found in the cartYESYES
Bootstrap enabled UIYESYES
Cart page that lists all products added to cartYESYES
Auto compute the total cost of all products added to the cartYESYES
The navigation bar has to drop down of product categoriesNOYES
Highlight selected category in the dropdownNOYES
Categories are retrieved from the databaseNOYES
Show products by category with paginationNOYES
Search products with paginated resultsNOYES
Search box located on the upper right corner of the navigation barNOYES
Search box requires search term before clicking the search buttonNOYES
Input quantity beside the add to cart button with value required to be a numberNOYES
Quantity input required to have a minimum value of 1, negative value not allowedNOYES
Remember the page number where the user clicked the “Add to cart” buttonNOYES
Quantity drop-down options based on available stockNOYES
Well formatted money valueNOYES
Product image viewable in a lightbox pop-upNOYES
Shows number of stock leftNOYES
Stock decreases once checked outNOYES
Order saved in orders and order_items table in the databaseNOYES
Empty cart button with confirmation popupNOYES
Show price, category, and stocks left on the product list pageNOYES
Free code updates and supportYESYES

How to run the source code?

Once you downloaded the source code, here’s how you can run it.

  1. Extract the files to your server directory.
  2. Go to your PhpMyAdmin, create a database with a name “shop_cart_sessions_1”.
  3. Import the “shop_cart_sessions_1.sql” file located in the “README” folder.
  4. You might need to change database credentials in /config/database.php
  5. Run “products.php”, this is the main PHP file. We do not have index.php

Need more features?

PHP Shopping Cart Module. You can download our “PHP Shopping Cart & Ordering Module” source code. It has several features you need to learn more about how to handle the users, shopping cart, and ordering using the PHP & MySQL technology. CLICK HERE TO LEARN MORE

PHP Shopping Cart System. You can download our “PHP Shopping Cart System” source code as well. Many of you requested this type of source code and not it is here!

You needed a shopping cart system with user management (merchant and customer), product management, order management, security, and more features based on our source codes here in codeofaninja.com. CLICK HERE TO LEARN MORE.

What’s Next?

Option 1: We just learned how to code an online shopping cart from scratch using PHP SESSIONS. But did you know that we can create 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

Option 2: This next tutorial is the start of our JavaScript programming journey. Go to our next tutorial: How To Create a Simple REST API in PHP – Step By Step Guide!

[adinserter block=”1″]

Some Notes

[adinserter block=”3″]

Thank you for studying our PHP Shopping Cart Tutorial using SESSIONS! Please share our tutorial with your friend.


Comments

277 responses to “PHP Shopping Cart Tutorial using Sessions”

  1. Leonardo Avatar
    Leonardo

    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.
    So, I wanted to ask you: Do you think sessions is the right way of doing this?
    I think in a production site this wouldn’t be the best thing to do.
    Shouldn’t you save all the cart stuff in the database right when the user interacts with it? Using some ajax maybe?
    Or is it the idea to save the sessions in the db when the user clicks ‘see cart’ or something?
    I’m asking you this, becouse i’m working in an e-commerce proyect and I was just looking at your blog and saw this post.
    Well, thank you very much man. I really admire your work.
    Leonardo.

    1. Hi Leonardo, thank you very much for appreciating my works and sharing your thoughts!

      I think using PHP session is a faster and lighter way to handle cart items because it reduces your server load/work. It doesn’t have to do lots of extra queries like INSERT and DELETE.

      But if your project requires tracking of what items were added or removed from cart, you should probably use a database.

      Normally, when the user do a ‘check out’ you should save (to the database) all the items from his cart (for purchase history purposes), but unfortunately, this tutorial focuses on retrieving/adding/removing product items from cart.

      1. how to check out ? … like store the selected items permanently under a users id .

  2. Sathish D Avatar
    Sathish D

    I found another interesting Shopping cart design here: http://www.quora.com/E-Commerce/What-is-the-shopping-cart-used-in-SQLyog-website

    1. Hi @google-91cf1cede8bee7ae3d99845a71c2df98, thanks for dropping by and sharing a shopping cart design!

  3. Ibrahim Avatar
    Ibrahim

    thank you so much for sharing that great work with us it really helped a lot.
    would it be too much to ask you to modify the code so that costumers can choose the quantity of the product they want please?
    again you have saved me so much time thank you.

    1. You’re welcome @7e859c986b5f02f7f383df73b264cb5d! If you want to add that feature, you can do that in the Cart.php, add something like:

      on the heading inside the th tags will be “Quantity”

      and inside the loop…

      I hope that will give you a good start!

      1. Thanks for replying, adding a row in the table for quantity is basic step what about processing it? can you please give code for a new page updateCart.php and mechanism to update quantity of the product. Thank you

  4. Chrissy Avatar
    Chrissy

    I uploaded the files as is to my hostgator hosted website but when I click on the products page I get an error:

    “Connection error: SQLSTATE[28000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO)Fatal error: Call to a member function prepare() on a non-object in/home/user/public_html/shopping list test files/Products.php on line 33”

    Does anyone know what I need to do to fix this? I’m assuming I need to add in a password or something, but I really have no clue on how to do that.

    Anywho, thanks for the great tutorial! Now I just need to figure out how to make it work.

    1. Hi @Chrissy, thanks for dropping by, I think you just have to fix your MySQL database login credentials. Sorry, I’m not familiar with hostgator…

  5. Sai Ch Avatar
    Sai Ch

    ( ! ) Notice: Undefined index: cart in C:wampwwwshopcartNavigation.php on line 2
    Call Stack
    #TimeMemoryFunctionLocation
    10.0028138256{main}( )..index.php:0
    20.0064140752include( ‘C:wampwwwshopcartNavigation.php’ )..index.php:16

    every script contains error like ” Notice: Undefined index” plz help me

    1. Hi @sai_ch, you can use the isset() function to check the ‘undefined index’, something like $yourVariable = isset($_REQUEST[‘your_index’]) ? $_REQUEST[‘your_index’] : “”;

  6. Nayem Avatar
    Nayem

    thanks, for this code it’s very helpful for me…………

    1. You’re welcome Nayem! You can share or subscribe if you have time 🙂

  7. Jothon Ropero Avatar
    Jothon Ropero

    wow this is amazing. very helpful

    1. Thanks @jothonropero! 🙂

  8. Gustavo Caso Avatar
    Gustavo Caso

    I still get confused with $_SESSION . When did you initialize $_SESSION[‘cart’] ? .
    Thanks I know the question might be stupid, but any help is great.

    1. Hi @gustavo_caso, it was initialized in AddToCart.php

      if(!isset($_SESSION[‘cart’])){
      $_SESSION[‘cart’] = array();
      }

  9. Gustavo Caso Avatar
    Gustavo Caso

    I’m not able to get the shopping cart to add more than one product to the cart .
    Any help please.

    1. Thanks for dropping by @gustavo_caso! any error message you see?

      1. Gustavo Caso Avatar
        Gustavo Caso

        Yes @ninjazhai. The variable $ids. only get one element so the query is not able to get more than one element . Thanks for your quick answer.

  10. ashinga Avatar
    ashinga

    Cool script 🙂 very helpful for a kick start

    1. Thanks @427cee5eba447df762e32f0779476914! 🙂

  11. ive got a problem here Notice: Undefined variable: _SESSION in C:wampwwwexamplenavigation.php on line 3

    1. Hi @disqus_VFFRaOd1U2, please read my answer to other comments.. you can also use this code to the PHP file you’re currently browsing:

      if(!isset($_SESSION[‘cart’])){
      $_SESSION[‘cart’] = array();
      }

      1. hi mike how can i fixed the problem to me about the object/product.php i have a little bit problem about public count(){

        }

        1. Hi @jetro, would you tell us the error message you encounter?

    2. For those still having the issue, I updated the code above, including the download, please try and tell us if it works or not. Thanks!

      1. Akshay Rajpure Avatar
        Akshay Rajpure

        dear Mike, you updated code but i didnt get the updated file can you share the location of file

        1. Hi @akshayrajpure , I assume you downloaded our source code. You can search your email with keywords “sellfy” where you can find the download button.

    3. Hi guys, it looks like many of you up-voted this comment NOT because of the error on the navigation.php file, but because I missed to include the navigation.php file code on the tutorial above.

      What happend was I accidentally leave out the navigation.php file when I recently updated the tutorial above. No one commented “navigation.php file & code is missing”.

      Next time, I’ll be more careful when updating our tutorial. If you found a bug, please let me know immediately and be descriptive on the problem so I can take action faster. My email address is [email protected]

      I’m very sorry for the confusion. I added the navigation.php code in section 5.2 above, all thanks to @disqus_oA8v8AP1xq for brining this to my attention.

  12. Sumit Kumar Avatar
    Sumit Kumar

    hi Ninjazhai
    Grating of the day.
    I hope you fine.
    here my some problem please guide me …
    I m Trying to build Chat app. in my website with Login only unique id ans also store every chat history in my database;i can’t understand how to do please give me some guideline.

    sumit kumar([email protected])

  13. The code is written very badly! Sessions are not initialized properly!!! And it is very confusing with all those files having same code repeating over and over.. It needs some cleaning because doesn’t work at all. I don’t know why it works in the Demo! Anyway Great Post 😛

    1. Hi @127d8a9b05e560a8c5719cba73f10c68, can you site how sessions should be initialized in this case? And which files have the same code?

      I agree that this code needs some cleaning, optimization and security, because this is not a production-ready code, this is just an example code that can give someone an idea how a shopping cart script can be done and started from scratch.

      I don’t know why it does not work for you, most people find this code working. I’m a little confused by your comment, you said this is not working but you also said this is a great post?

  14. are you still here?? 😀 i tried this code but the product name and price wont display. only the table. i checked my variables and index and it’s ok. why oh why?? 😀

    btw, thanks for this one 🙂 it helps me with our assignment.

    1. Hi @46300fdf613aa5b66206c5793e23d40c, can you give us which file you’re having the error with? and also post the error message and the code you used..

  15. hello can i ask you how to save the shopping cart of you

    1. Hi @disqus_DMPncTtjAZ, you can retrieve the products in the session array and save it in your database http://www.codeofaninja.com/2012/01/pdo-create-record.html

  16. hello. i used this code and it only adds the first item in my database. and it replaces the name of the item that is added to number “1”. like 1 is added to your cart and 1 exist in your car(both shows when i add the first item). why is that? btw, thanks for the code 😀

    1. Hi @disqus_qvfIyzKeld, thanks for visiting! can you post your code? did you use a loop? also, make sure you use proper indexes so it won’t replace the first record.

      1. i solved it. thanks 🙂

  17. thanks for this code

    1. You’re welcome man!

  18. why can’t i view the contents of my cart? 🙁

  19. Notice: Undefined index: action in E:wampwwwshopping-cart-in-phpProducts.php on line 22 and 26

    getting this error.please help me how to fix this and mostly all are working fine.

    1. Hi @78d9cfc3e84ad63c1444238fa6720893, you can check if the action is defined in this way, add this code before line 22

      $_GET[‘action’] = isset($_GET[‘action’]) ? $_GET[‘action’] : “”;

  20. Akshay Chauhan Avatar
    Akshay Chauhan

    i am getting the following errors when i click ‘view products’ and ‘view cart’
    Notice: Undefined variable: con in C:xampphtdocsshoppingcartProducts.php on line 35

    Fatal error: Call to a member function prepare() on a non-object in C:xampphtdocsshoppingcartProducts.phpon line 35

    and

    Notice: Undefined index: action in C:xampphtdocsshoppingcartCart.php on line 20

    Notice: Undefined variable: con in C:xampphtdocsshoppingcartCart.php on line 36

    Fatal error: Call to a member function prepare() on a non-object in C:xampphtdocsshoppingcartCart.php on line 36

    can you please tell me what’s wrong? Thanks

    1. Hi @disqus_CMlsLbCS8A , did you connect to the database like this? http://www.codeofaninja.com/2012/01/pdo-connect-to-mysql-database.html

      1. i did it using mysql_connect function, but now that i have used your way of connecting, i am getting Connection error: SQLSTATE[HY000] [1049] Unknown database ‘coan_shop’.

      2. ok i solved it, thank you very much for your prompt reply 🙂 🙂

        1. Glad it works now @a144479df4b582f66d3eb896ccb09071!

      3. Hi, thank you for the reply, it worked with the PDO way. But now on clicking view cart i have the error of ‘undefined index: action’ in cart.php. I am new to php, but this was really helpful, thank you.

      4. Akshay Chauhan Avatar
        Akshay Chauhan

        Thank you, i figured it out. Well done.

        1. Good to hear it works now @disqus_CMlsLbCS8A!

  21. i am getting these errors
    Notice: Undefined variable: con inC:xampphtdocsshoppingcartProducts.php on line35

    Fatal error: Call to a member function prepare() on a non-object in C:xampphtdocsshoppingcartProducts.phpon line 35

    please help

  22. Cheenu Meenu Avatar
    Cheenu Meenu

    ” Notice: Undefined variable: conprepare in E:STUDY ROOMwampwwwshopping cartproducts.php on line 35 ”

    Fatal error: Function name must be a string in E:STUDY ROOMwampwwwshopping cartproducts.php on line 35

    please sir give me the answer of these errors what can i do?

    1. Hi @cheenumeenu, are you sure you are properly connected to the database?

  23. Hi, I found this error:

    In view Product:
    Notice: Undefined index: action in C:xampphtdocssampleProducts.php on line 22
    Notice: Undefined index: action in C:xampphtdocssampleProducts.php on line 26

    In View Cart:
    Notice: Undefined index: action in C:xampphtdocssampleCart.php on line 20

    and view cart shows (1) instead there are no product inside.

    Please help me…

  24. Hi,

    I got problem with the

    1. Home page it shows

    Notice: Undefined index: cart in C:xampphtdocssampleNavigation.php on line 2

    2. Product Page it shows

    Notice: Undefined index: cart in C:xampphtdocssampleNavigation.php on line 2

    Notice: Undefined index: action in C:xampphtdocssampleProducts.php on line 22

    Notice: Undefined index: action in C:xampphtdocssampleProducts.php on line 26

    3. Shopping Cart Page shows

    Notice: Undefined index: action in C:xampphtdocssampleCart.php on line 20

    Please help me..

    1. Hi tracy, you can solve that by checking if an index was set, for example in you ‘action’ variable:

      $action = isset($_REQUEST[‘action’]) ? $_REQUEST[‘action’] : “”;

  25. Congratulations first of all for your codes , I did download your Code which is above , but on my machine when i want to run it , it says Demo is not available , shall i understand in that zip files is not the full project ? can u help me with that please ?!

    1. Thanks @disqus_e6KNExHSur! The zip file should run like the demo above, did you installed a server on your computer? You can follow this tutorial first http://www.codeofaninja.com/2013/06/installing-wamp-on-windows.html

  26. hi, when i add my products to the cart the cart count on products page increase, but when i click ‘view cart’ it says ‘No products found in your cart. :(‘ ?? how to resolve? tq

    1. Hi @fsdm, do you see any error message? please check you sql query…

    2. Raden Remerata Alvarez Avatar
      Raden Remerata Alvarez

      i got the same error to i followed the steps and also the variable declaration but still i got this error ‘No products found in your cart. :(‘ the sql statement SELECT id, name, price FROM products WHERE id IN ({$ids}) not recognizing the array list from ids??

      1. Hi @radenremerataalvarez, would you print what’s inside your $ids? You can do something like: print_r($ids);

        1. Raden Remerata Alvarez Avatar
          Raden Remerata Alvarez

          The product Id from the dtabse

          1. you can also echo your sql statement and find out what’s wrong…

          2. Raden Remerata Alvarez Avatar
            Raden Remerata Alvarez

            still same =( error no progress

  27. Nico Mora Avatar
    Nico Mora

    i got this error, what should i do?

  28. Nico Mora Avatar
    Nico Mora

    i got this error, what should i do?

    1. Hi @nicomora, are you sure you were properly connected to the database?

      1. Hello This is the error for me i dont know how to fix this

  29. hello

    this is my problem. can you help me please ((@ninjazhai ))

    1. Hi @disqus_NzRS4RAdcs, are you using wamp? I think your server does not support pdo…

  30. hi.. im nabeel, iv got a problem, how to over come? this is the error

    Notice: Undefined variable: con in C:wampwwwcart_phpProducts.php on line 37

    1. Hi @disqus_OuEaaazs40, please check your db_connect.php file and make sure it was included in you products.php

  31. i got this problems:

    Fatal error: Call to undefined method mysqli_stmt::rowCount() in C:wampwwwshoppingcartoriginalProducts.php on line 40

    even those wampserver php extention php_pdo_mysql is enable.

    1. Hi @gino, are you sure you have the MySQLi extension?

  32. hii i am not able to see any products…..

    1. Hi @disqus_PsanOnEwCv, do you see any error messages? Probably in you products.php…

  33. hi. what to do if my server didt support PDO?

    1. Hi @aaron, well, you’ll have to learn the syntax of either mysqli or mysql (not recommended) extension, this might help you http://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  34. How can one change the picture per table cell?

    1. ninjazhai Avatar
      ninjazhai

      Hey @ninjaz, how about saving the image url to your database and later access it?

  35. its helpful to me i did something…..but i also i need disabling code can i?
    thanx

    1. ninjazhai Avatar
      ninjazhai

      HI @disqus_PxewpCMGPA, what exactly do you want to disable?

  36. Mystro Odei Avatar
    Mystro Odei

    hi it seems u didnt add the connection file to the zip file so some of the functions are not working. pls check that and by the way this is awesome work bigups.

    1. ninjazhai Avatar
      ninjazhai

      hi @mystroodei, thanks for pointing it out, do you mean the DbConnect.php file?

      1. Mystro Odei Avatar
        Mystro Odei

        yes that exactly i think with that every bodies problem would be solved. thanks for your time

      2. Mystro Odei Avatar
        Mystro Odei

        please have you uploaded the Dbconnect.php already

  37. Soujiro Seta Avatar
    Soujiro Seta

    I’ve got problem here Fatal error: Call to a member function prepare() on a non-object in C:xampphtdocsshopping-cartCart.php on line 39

    1. ninjazhai Avatar
      ninjazhai

      hi @disqus_ZGAZGJEW00, I think the problem lies with your database connection file, see 4.1 of this post http://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  38. drvipinlalt Avatar
    drvipinlalt

    can you please help me… at last i want to add user name, phone number and add this whole things to database. any idea…

    1. ninjazhai Avatar
      ninjazhai

      Hi @drvipinlalt, how about creating a new table using your phpmyadmin, and adding the php file with html form field based on your new table? this php crud tutorial might also help you http://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  39. Carl Justin Guinto Avatar
    Carl Justin Guinto

    where is the codes for “(libs/DbConnect.php) ?

    1. nicolous Avatar
      nicolous

      yes where is (libs/DbConnect.php) ?

    2. nicolous Avatar
      nicolous

      can you give us the codes for that ?

  40. What about update the quantity and the price

    1. Yes please what about updating product quantity and price?

  41. nicolous Avatar
    nicolous

    can you help for the codes of (libs/DbConnect.php) ?

  42. nicolous Avatar
    nicolous

    would you help me about the (libs/DbConnect.php) ?
    pleasseeeeeeeeee 🙂

  43. Ayane Avatar
    Ayane

    Can somebody tell me what tags and variables should i change in Products.php if im using this table, im confused due to variables using same names and dont know where exacly i should or shouldnt change the original variables for mine.

    CREATE TABLE Articulos(
    OID_A SMALLINT NOT NULL,
    Descripcion VARCHAR(200),
    Precio NUMBER(6,2),
    PRIMARY KEY(OID_A)
    ) ;

    OID_A instead of ‘id’
    Descripcion instead of ‘name’
    precio instead of ‘price’

    thnx

  44. Hello Mike, I love your work and you are doing a very noble work by teaching people like me, without any charges and stuff.

    I had been looking for a mentor to teach me how to write a shopping cart from scratch. Then I stumbled upon your Shopping Cart code and it is great. Now I finally know how to do it. I can’t thank you enough but I have a really urgent request, can you please explain to me how I can add Quantity to shopping cart? like oscommerce where you can update the quantity.

    I will be desperately waiting for your reply. Thank you

  45. Hi,

    Great job. I repaired some rows and your cart is working. 🙂

    some repair:
    // require “libs/DbConnect.php”;
    include(“libs/DbConnect.php”);

    – Products.php and other files the same as:

    $query = “SELECT id, name, price FROM products”;
    $rst = myQuery($query);
    // $stmt = $con->prepare( $query );
    // $stmt->execute();

    $num = mysql_num_rows($rst);

    // $num = $stmt->rowCount();

    if($num>0){
    echo “”;//start table

    // our table heading
    echo “”;
    echo “Product Name”;
    echo “Price (USD)”;
    echo “Action”;
    echo “”;

    while ($row = mysql_fetch_array($rst)) { // while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

    -db_connect:

    function myQuery($qry){
    $con = mysql_connect(“localhost”,”db”,”pass”);
    if(!$con)
    return false;
    $db = mysql_select_db(“name”,$con);
    if(!$db)
    return false;

    mysql_query(“SET NAMES UTF8”);
    $rst = mysql_query($qry);
    mysql_close($con);
    return $rst;
    }

    thank’s your job

    Yours,
    Tom

  46. joaozinho20 Avatar
    joaozinho20

    Hey bro.
    That works just fine if you are showing the data of 4-5 produts, but more than that the webpage just goes down and down …
    Do you have any tuturial in how to show like until 5th product and then we can go to another page?
    Like pagination through the Cart …
    Thanks and good night

  47. please what is the name of the db created in this tutorial for our table “product”?

    1. ninjazhai Avatar
      ninjazhai

      Hey henry, you can put any name on your database, as long as the tables are almost the same with those above!

  48. kirti tonk Avatar
    kirti tonk

    superb code…… 🙂 very helpful….. 🙂

  49. Kwabyna Nkrumah Avatar
    Kwabyna Nkrumah

    $con undefine.. please help me

    1. ninjazhai Avatar
      ninjazhai

      Hey @kwabynankrumah , I think you should learn the basic php crud first, take a look at this http://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  50. ninjazhai Avatar
    ninjazhai

    Hey ron, you can do that with the help of this PHP login tutorial http://www.codeofaninja.com/2013/03/php-login-script.html

    1. I’d strongly recommend you do not save against a userid in the form of cookies, it’s a really bad idea if you aren’t encrypting your data and enforcing encryption.

      Use a randomly generated cart/session id for that purpose it’s really I hate to be blunt but it’s a massive security hole.

  51. ninjazhai Avatar
    ninjazhai

    Hey thanks for your suggestions, I will update this post with those features!

  52. lanner Avatar
    lanner

    hello
    How to add the same product more than 1 time ?

    1. ninjazhai Avatar
      ninjazhai

      Hey @lanner, currently, this code does not support changing product quantity…

  53. what is your database name?

    1. ninjazhai Avatar
      ninjazhai

      Hey @su, my database name is called “sampledb”

  54. Jeremy Smith Avatar
    Jeremy Smith

    Words can’t express how greatful 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!

    1. ninjazhai Avatar
      ninjazhai

      Hello @disqus_Tkg3Hukomt, thanks for the kind words! Please don’t hesitate to share your comments regarding any article here so that it will keep on improving with the help of people like you! Thanks!

  55. Without wanting to cause any offence it does create a little bit of traffic between the client and the server, since with sessions you have to have a file on the server and the clients browser (cookie), your real best bet’s to use pure cookies, though with the likes of bandwidth increasing can be done of course using the above.

    1. ninjazhai Avatar
      ninjazhai

      For those who are reading this, please see my other reply to Jeremy below.

  56. Also sorry I could not put this into my first post about why you should not use sessions, if there was a disk failure or for some reason someone was to remove all sessions from the sessions location (defined in the php.ini file) then the person viewing the cart all items would disappear, with the earlier example where someone was to remove the cookie files from the servers file system using just cookies and not sessions they wouldn’t disappear.

    The above’s probably the most critical reason really not to use sessions, but as tutorials go, this is a great potential example 🙂

    1. ninjazhai Avatar
      ninjazhai

      Hello @Jeremy, you got some good points there, I really appreciate your effort to improve this post! Your comments are well detailed to be a starting point for new development and contains true arguments about the subject.

      WooCommerce was using PHP sessions for cart data before, but last year they changed it and are now using cookies. I think that’s also a big example and reason why we have to use cookies for storing cart data. See their version 2.0.0 change log here http://wordpress.org/plugins/woocommerce/changelog/

      I will have to create another post on how to use cookies to store cart data. Thanks again for bringing this to my attention!

      But still, as you said, the tutorial above is a great potential example for understanding how shopping carts work before, and still a good example for low traffic shopping website.

      1. I believe in improving peoples skill sets no matter what when it comes to ecommerce, I mean there’s always multiple ways of doing various things and having a background knowledge on how mysql works in a technical sense I know people would love to see.

        Of course I’d be honoured to help anyone that wants it or whatever, thank you so much for saying that I really appreciate it! Take care of yourself 🙂

      2. To be honest, cookies or sessions would be fair enough to use on a second thought actually, mainly because if there was such an error (I think I said on the serverside, either hard drive fail or whatever) you’d not be able to see anything anyway.

        Be interesting to see what the pitfalls are for either.

  57. Notice: Undefined variable: id in C:xampphtdocsFish_fansPurchase.php on line 89
    line89 —> echo ““;

    what is the problem?
    T_T…help~~thanks

    1. ninjazhai Avatar
      ninjazhai

      Hey @windy, are you sure you have a variable called $id in your code? It’s hard to debug since I can’t see your page source code..

  58. Joe Koder Avatar
    Joe Koder

    If you turn up the PDO connection error reporting you will see you have a problem with a query being run on an empty cart. on line 40 of Cart.php. To see the error, add this to your DB connection:

    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    The problem is when there are no items in the cart, a bad query is sent to the DB and causes an error that you never know about with the existing code.

    This is the actual query sent with no cart items:
    SELECT id, name, price FROM products WHERE id IN ()

    Since the cart is empty, a call to the database for products should not be made.

    Here is the simple fix:

    Cart.php: Change line 27
    FROM

    if(isset($_SESSION[‘cart’])){

    TO

    if(!empty($_SESSION[‘cart’])) {

  59. Notice: Undefined variable: con inC:xampphtdocsEcommersProducts.php on line 37

    Fatal error: Call to a member function prepare() on a non-object in C:xampphtdocsEcommersProducts.php on line 37

    Can you help me to fix this problem I really want to see the output of it too and Thanks for the help in my other project it really help me alot

  60. Fatal error: Call to a member function prepare() on a non-object in C:xampphtdocsEcommersProducts.php on line 37

    Sir can you help me on this error

  61. ninjazhai Avatar
    ninjazhai

    Hey @carl, are you sure you are connected to the database properly? You can check this tutorial for reference http://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  62. Louis Blais Avatar
    Louis Blais

    Hello, This is a great script and I have paid 6.99 for your work (it Worth it). But I got something wrong: Warning: array_key_exists() expects parameter 2 to be array, null given… …on line 56 ( I got this error when I open products.php for the first time.
    Also you should think to Add a pagination in this code.
    Cart price total should appear next to the icon.
    I know i’m late to post in this thread, but I hope you’ll read it!

    1. ninjazhai Avatar
      ninjazhai

      Hi Louis Blais, thanks for downloading our code! Regarding your issue, you can try to add the code below before the while loop:

      if(!isset($_SESSION[‘cart’])){
      $_SESSION[‘cart’]=array();
      }

      Thanks also for all your suggestion, I’ll work on that and you’ll get the free update! 😀

      1. Louis Blais Avatar
        Louis Blais

        Thank you very much! You did a great script. Tonight I will try your code.
        Thanks again! 🙂

    2. ninjazhai Avatar
      ninjazhai

      Hello @louisblais, thanks for purchasing the code and kind words! Did you receive an email update on this source code? I have fixed any possible issues on the latest update.

  63. saishyam Avatar
    saishyam

    i am getting this error pls help:

    Fatal error: Call to undefined method mysqli_stmt::rowCount() in D:xampphtdocsproducts.php on line 28

    Notice: Undefined index: cart_items in D:xampphtdocscart.php on line 22

    1. ninjazhai Avatar
      ninjazhai

      Hey @saishyam, we’re using PDO extension in the tutorial above.. I don’t think rowCount() will work for MySQLi…

    2. sameena banu Avatar
      sameena banu

      heyy @saishyam ,

      even im getting the same error,

      Notice: Undefined index: cart_items in D:xampphtdocscart.php ,
      did u solve dis error ? if yes, can u plzz help me to solve this…

      1. ninjazhai Avatar
        ninjazhai

        @sameena_banu, you can use the PHP isset() to solve it.

  64. Charles Harris Avatar
    Charles Harris

    Mike ?

    Does your “downloadable” version have more functionality past the checkout stage? – I clicked checkout on your demo version and nothing happens. I need something solid and simple like this to integrate into a existing portal but need the checkout function to email the buyer and the owner of the store an email with order info and place the order into a separate table for financial tasks.. where can i view the full demo or is this it ?

    Regards
    CH (Sam)

    1. ninjazhai Avatar
      ninjazhai

      Hello Charles,

      It doesn’t have more functionality past the checkout stage. The demo is as is.

      What I’m currently working on is the admin section for products and its login script. More features will come but not yet on the online payment part for now.

  65. Hello Mike, the level 2 live demo search and category don’t working.

  66. Show Products in Category: Coming Soon in category.

    1. ninjazhai Avatar
      ninjazhai

      @Gomes, yes I’m working on it.

  67. sameena banu Avatar
    sameena banu

    hii,
    thanx for the code..it is really awesome .but i need to add the items in the cart to the database and also the code for checkout..i will be really greatfull if you could help me …plzzz

    1. ninjazhai Avatar
      ninjazhai

      Hello @sameena_banu, thanks for the interest, I’m releasing it before the end of March 2015, stay tuned!

  68. ninjazhai Avatar
    ninjazhai

    Hello @Gomes, maybe there’s a problem with your implementation, what error do you see? It works on our live demo.

  69. bastiaan Avatar
    bastiaan

    hi, i would like to have this customized. Is this a possibility ? you can find me via skype @ bastiaan.schreuder

    1. ninjazhai Avatar
      ninjazhai

      Hello @bastiaan, and for all others who want customization, please send me an email at [email protected], we can talk about more details there! Thanks!

  70. Hi, is it possible to change the quantity input to start from 100 up in 100 steps (like 100,200,300 etc) to max. 1000 ?

    1. ninjazhai Avatar
      ninjazhai

      Hello Frank, you can use tag instead for that purpose…

  71. Hi, for some reason the subtotal, total and the quantity don’t work: http://www.tracadite.com/products.php pls help

    1. ninjazhai Avatar
      ninjazhai

      Hello @disqus_z4MwpilrzH, would you tell us the error message you saw? Sorry but I can’t see your page anymore…

      1. Oh sorry it’s here: http://www.tracadite.com/cart/products.php basically when you add something to the cart, the subtotals, totals and quantities don’t show up.

  72. hi.. i have a question about the codes…

    you know Mr/Mss.programmer I copy all the given steps but why thers an error..

    my error is “Fatal error: Call to a member function prepare() on a non-object in” what should i do??

    can you please help me for this??

    1. ninjazhai Avatar
      ninjazhai

      Hello @Judy Ann, are you sure you’re properly connected to your MySQL database?

  73. bg17aw Avatar
    bg17aw

    header(‘Location: products.php?action=added&id’ . $id . ‘&name=’ . $name);

    Aren’t you missing an = sign after “&id” ?

  74. maehem Avatar
    maehem

    hi, i’m maehem… my problem is that i keep on getting an error of “undefined index: cart” in navigation.php and cart.php…… pls help………

  75. Eric Wunderlich Avatar
    Eric Wunderlich

    Hi, it’s a nice code you have here, i just have a problem, when i put it in my server and tried to enter in products.php, an error saying Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /home/huntingd/public_html/products.php:9) in/home/huntingd/public_html/products.php on line 10 i dont know what i going on there

    1. ninjazhai Avatar
      ninjazhai

      Hello @Eric, I believe these kinds of issues were solved on our recent updates, thanks for reporting the issue!

  76. Dean1984 Avatar
    Dean1984

    Hey, Massive thanks for this! Have you got the categories section working yet?

    1. ninjazhai Avatar
      ninjazhai

      Yes it works now @Dean1984, please check out the LEVEL 2 live demo above. But if you’re interested in more features, the LEVEL 3 source code is worth checking out!

  77. Dean Marshall Avatar
    Dean Marshall

    Hey, Massive thanks for this! have you got the categories section working yet?

    1. ninjazhai Avatar
      ninjazhai

      Hello Dean, you’re welcome! Thanks for the interest, I’m releasing a new update on the third or fourth week of March 2015, with the Level 3 source code (admin, user features, and more.)…

      1. Dean Marshall Avatar
        Dean Marshall

        Great, looking forward to it. Good work and thanks again!

        1. ninjazhai Avatar
          ninjazhai

          Hello @disqus_NxELTP5icu and @ashleydeannaplata, did you receive the update notification (via email) on the LEVEL 2 source code? Also, LEVEL 3 source code is now available, you can check it out on the article above. 🙂

          1. Dean Marshall Avatar
            Dean Marshall

            Hi, I did Thank you! I have just downloaded the level 3 source code so many thanks 🙂

          2. ninjazhai Avatar
            ninjazhai

            Thank you for downloading the code! Please see above (after the LEVEL 3 features table in section 7.4) for a simple configuration needed when you install the LEVEL 3 source code. Chat me up if you encounter any other issues, thanks again!

      2. AshleyDeanna Plata Avatar
        AshleyDeanna Plata

        Hi there! Do you have codes for checkout?
        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!

        1. ninjazhai Avatar
          ninjazhai

          Hello @ashleydeannaplata, thanks for purchasing the code, glad it was a very big help for you! I’m releasing a level-3 source code before the end of March 2015. Check out code will include COD and Bank Options… and eventually PayPal payment in the future. Thanks for your interest!

          1. when will the paypal payment be added?

          2. WherE can I purchase this add on?

  78. Man, your tut’s are awesome. Im so glad ive found your blog. Big respect!

    1. ninjazhai Avatar
      ninjazhai

      Hello @Milos, thanks for the kind words! I’m also glad you are visiting our site, thanks again!

  79. SQL Injection Vulnerability Avatar
    SQL Injection Vulnerability

    Hey, you got a giant SQL injection vulnerability in your tutorial code, which allows attackers to execute arbitrary SQL commands on the database.

    The way you construct your SQL queries is NOT SAFE. Do not use this code until it is fixed. You should NEVER stitch together SQL queries like this. ALWAYS use prepared statements and parameter binding.

    The keyword is “SQL Injection” and there’s plenty resources on the web.

    1. ninjazhai Avatar
      ninjazhai

      Hello there, first of all, I really appreciate your comment and I wanna thank you for bringing this to my attention, I quickly fixed the issue, I found the vulnerability in the search.php file.

      Here is the solution, please change the query code in search.php, find this part of the code:


      $query = "SELECT id, name, price, category_id FROM products WHERE name LIKE "%{$search_term}%" ORDER BY name LIMIT {$from_record_num}, {$records_per_page}";
      $stmt = $con->prepare( $query );
      $stmt->execute();

      …and then CHANGE IT to this one:


      $query = "SELECT id, name, price, category_id FROM products WHERE name LIKE ? ORDER BY name LIMIT {$from_record_num}, {$records_per_page}";
      $stmt = $con->prepare($query);
      $search_term = "%{$search_term}%";
      $stmt->bindParam(1, $search_term);
      $stmt->execute();

      I sent an email update to those who downloaded the source code.

      1. SQL Injection Vulnerability Avatar
        SQL Injection Vulnerability

        This is the correct approach, but you’ll need to fix each occurrence.

        The line

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

        is still exploitable. There may be more, I stopped after this one.

        Security holes like this in a shop system are more than scary – one could change prices and place orders. I think I’d go for negative prices.. 😉

        1. ninjazhai Avatar
          ninjazhai

          Hi there, oh yes I also saw this one coming, I just fixed the more obvious one first, I’m gonna send another update. And yes, the negative prices when you selected a negative quantity, I’m fixing that too… Thanks again!

  80. ninjazhai Avatar
    ninjazhai

    Hello bg17aw, oh yes, you’re right, please make it like this:


    header('Location: products.php?action=added&id=' . $id . '&name=' . $name);

  81. ninjazhai Avatar
    ninjazhai

    Hello @AHAK, sorry for the late reply, I just read your comment, do you still need this feature? I believe it’s included on our code update above that you can download. But thanks for the kind words!

  82. ninjazhai Avatar
    ninjazhai

    Hello @maehem, I believe these kinds of issues were solved on our recent updates, thanks for reporting the issue!

  83. ROBINASO Avatar
    ROBINASO

    Hi, my name is Bob.

    I have to use an xml database. How can I change the connection to the database and retrieve data from It?

    Thanks

    1. Hello Bob, sorry but I haven’t try it with an XML database, how about you convert that database to MySQL?

      1. ROBINASO Avatar
        ROBINASO

        For business reasons I can use only an xml database. How to implement (simplexml_load_file) in your script.Thanks

      2. ROBINASO Avatar
        ROBINASO

        I use an xml database for business reason. I don’t Know How to use an xml file in your project.

        1. Hello @ROBINASO, you will have to use an extra script that converts your XML file to MySQL data.

          1. ROBINASO Avatar
            ROBINASO

            Thanks, but I’m not a master with php? sigh!!!!

          2. Well, you’ll always have to start small. I recommend this blog post https://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

          3. hello guy how can i add mpesa here in kenya

          4. Hello @brian, what do you mean by mpesa?

  84. This is also fixed on the latest code, just in case people are wondering…

  85. winry Avatar
    winry

    The source codes in this page is NOT for you if:
    —-You are an already an expert in PHP & MySQL programming.
    I like this reason though,. HAhaha XD.

  86. Manan Desai Avatar
    Manan Desai

    hey, i just downloaded level 2 and i don’t know where to find add to cart query which you used to add product in cart please i need it ASAP

    1. Hello @disqus_Xnp3gZnCjh,

      Thanks for purchasing the code!

      About your question, there is no add to cart mysql query because it was saved in PHP sessions.

      Should you have more questions, please email me at [email protected], thank you!

  87. hey mike my name is ravinder from india iam using same sessions for wishlist but i want to store the wishlist data into database table with user login can you explain please…. the code wil be shown above

    1. Hello @disqus_HeZUt5PMme, please refer to the following tutorial, it uses MySQL database instead of PHP sessions https://www.codeofaninja.com/2015/08/simple-php-mysql-shopping-cart-tutorial.html

  88. I bought Order #: 90N23592NG469201M, but as you send the order created

  89. Filippo La Vardera Avatar
    Filippo La Vardera

    I bought Order #: 90N23592NG469201M, but as you send the order created

    1. Hello @filippolavardera, would you tell us exactly the issue you are facing, please add more details, thanks!

      1. Filippo La Vardera Avatar
        Filippo La Vardera

        I customized the cart.php, but I do not understand how to send the cart by mail

      2. Filippo La Vardera Avatar
        Filippo La Vardera

        I customized the cart.php, but I do not understand how to send the cart by mail

        1. @filippolavardera I think what you want is a new feature for our LEVEL 2 source code. Send me an email: ninjazhai@[email protected]

  90. Hello @price, the PayPal feature was made to be a $30 add on. Thanks for you interest in this feature!

    1. how can i get it?

    2. How do I get it?

    3. I have purchased Level 3 already.

      1. Thanks for purchasing the code! Please send me an email at [email protected] and I’ll help you set it up.

    4. Where can I purchase?

  91. Jasmine Montez Avatar
    Jasmine Montez

    why doesn’t my cart.php show the number of items i’ve added into cart even though I have added them to cart???

  92. Hello Jasmine Montez, would you send us your test URL so we investigate more about the issue? To display number of items in your cart.php, you just have to put this code:

    echo count($_SESSION['cart']);

    1. Jasmine Montez Avatar
      Jasmine Montez

      Eh? Now it’s telling me that cart_items is “undefined index”

      1. Hi @jasmine, you try to use the PHP isset() function for cart_items

  93. Cláudio Henrique da Costa Pere Avatar
    Cláudio Henrique da Costa Pere

    function prepare()?
    function execute()?

    1. Hello @claudio, not really sure what your question was, but in case you want a little explanation of those functions, prepare() means preparing the mysql query for execution of function execute()

  94. if the user enters an invalid email address & username, how can I validate that? I know I can use regex in javascript but what about php

    1. Hello @tora, you can try to use something like


      if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {

      Or HTML5 email input type. There’s also a lot of PHP email validation regex online.

  95. DevinDev Avatar
    DevinDev

    Do you have a demo of Level 3? Does it support Authorize.net checkout? Considering purchasing today. Thanks.

    1. Thanks for your interest to our code @devindev! Yes we have, I just sent it to your [email protected] email

  96. Kal Smith Avatar
    Kal Smith

    How send an email, i have some questions because i want buy the code

    Greetings from Stgo Chile !

    1. Hi @disqus_ai54hY1Edq, which part of the code do you want the email sending feature? I can develop it for you. Send me an email at [email protected]

  97. Kal Smith Avatar
    Kal Smith

    HI, I want buy the code, but i have some question in the code of $9.9 can i update the Quantity ?

    1. Hello @disqus_ai54hY1Edq, the LEVEL 2 source code has the update quantity feature.

  98. Hey I just bought the package, It keeps saying that;Notice: Undefined variable: con in C:UsersUserDesktopphpthinghtdocspaypalcartcart.php on line 45

    Fatal error: Call to a member function prepare() on null in C:UsersUserDesktopphpthinghtdocspaypalcartcart.php on line 45

    Notice: Undefined variable: con in products.php on line 25

    Fatal error: Call to a member function prepare() on null in
    products.php on line 25

  99. Hello @Sorgi, thanks for downloading the source codes!

    Which source code level did you download? I tried our source codes and I was unable to replicate you issue.

    Based on your error messages, it looks like you did not include the database connection file. Please send more info on my email [email protected]

  100. David K. Avatar
    David K.

    For some reason the cart is not calculating the total price when add items to the cart and I go to the Cart page. Any idea why?

    1. Hello @disqus_HoGApC0spk, are you sure you got the same code as step 9 above? $total_price+=$price; should accumulate the total price.

      1. David K. Avatar
        David K.

        all fixed, my mistake!

  101. Josh Dunn Avatar
    Josh Dunn

    Hi, what a great tutorial. I bought this a few days ago and have already learnt loads! Thankyou so much! I have one question, I am trying to embed this in to a seperate application and it works fine, but the app already has a login section and when different users log in, I want to save the items stored in the cart to their user? Is this possible?

    Thanks

    1. Hello @disqus_2s7yg8qBz7, thanks for purchasing the code! Glad you learned a lot, you’re welcome!

      About your question, yes it is possible to save the cart items for each user. You have to create a new table. In this table, your system should save the user ID (currently logged-in user) and product ID (the product in the cart).

      This way, you can retrieve the cart items of each user. You might want to take a look at another version of this code, it saves the cart items in the MySQL database, not in SESSIONS, see https://www.codeofaninja.com/2015/08/simple-php-mysql-shopping-cart-tutorial.html

  102. Product Images???

    1. Hi @budkaye, thanks for the idea. Product images feature is currently in this source code https://www.codeofaninja.com/2016/04/php-shopping-cart-source-code-download.html

  103. Victor Avatar
    Victor

    Hello, I am looking to buy the level 3 tutorial for PHP but was wondering if you knew if I would be able to make something that uses logic.
    This will be used to make a job calculator where someone would just enter lengths and the rest will need be calculated and turned into exact parts.
    Thank you for your time,

    1. Hello @disqus_5KYzQeAYgl , we can do customized script, please send more details to my email: [email protected]

  104. Khuanchai Pongpraseart Avatar
    Khuanchai Pongpraseart

    you have Download ALL LEVELS in Separate Packages and demo LEVELS 3 ?

    1. LEVEL 3 means the features of LEVEL 1 and LEVEL 2 source code is integrated or (done in a different way) into LEVEL 3 source code package.

      ALL LEVELS means LEVEL 1, 2 and 3 are in separate package.

  105. Looks great, but what about multiple sizes of items? T-Shirts come in many sizes… ?

    1. Hi @budkaye , that feature is not yet included in our source code. But I’ll try to include it on our next update.

  106. I get this errror

    Connection error: SQLSTATE[HY000] [1044] Access denied for user ”@’localhost’ to database

    1. Hello @Joseph, it means you are not properly connected to your database. Please verify your database credentials and update your db_connect.php

  107. Leandro Navarro Rojas Avatar
    Leandro Navarro Rojas

    Hey Mike, Why your application in the demo the content is set and in my localhost not?. Thanks.

    1. Hello @leandronavarrorojas , you can use the code either in localhost or web server. You’re welcome!

      1. Leandro Navarro Rojas Avatar
        Leandro Navarro Rojas

        Thank you Mike for answering the question, but I mean your application in the demo, the content is smaller than mine. I want the contents of my application look smaller as your application. I show you comparison. What added feature you ?. Thanks again. Greetings from Peru!

        1. What is the resolution of your computer screen? I have no idea yet why this happens, this is my first time to encounter such issue.

  108. Flying Squid Avatar
    Flying Squid

    Hi, Thanks for this tutorial it is amazing. This works great on my local wampserver, but not when I upload my site to justhost server, as then when I click on the cart to view cart items only my navbar appears, no footer and no cart with cart contents! I can still view the product page and add items to the cart, but I cannot view the cart and the total price. Please advise if there is something different I should be doing when uploading it to an online server? My code mirrors yours but with my own navbar and footer..

    Built the site in bootstrap and rather new to shopping carts

    Many thanks

    1. Hello @flyingsquid , thanks for the kind words!

      About the issue you described, do you see any error message?

      Please give us your test URL so we can investigate more about the issue.

      1. Flying Squid Avatar
        Flying Squid

        Thanks for your quick reply Mike, I managed to sort it out in the end, so I have it working now. Also, is this PHP cart able to integrate easily with Stripe custom payment form? I have both working again now but not integrated with each other

        1. Hello @flyingsquid , glad it works for you now! I believe a customized code like the above would be easily integrated to a third party solution like Stripe.

          We were able to integrate it in PayPal, see: https://www.codeofaninja.com/2016/04/paypal-integration-in-php.html

          Though I haven’t tried it with stripe yet because it is not supported in our country.

  109. Sir just yesterday i purchased level 2
    one of my query is how can i get code in mysqli or how can i convert

    1. Hello @Edhik , thanks for downloading the source code! I sent you an email regarding this matter.

  110. DoublePrince Avatar
    DoublePrince

    Hey Mike, my name is Martin, a computer science student in Nigeria. I have been visiting many sites checking for ways to learn how to use sessions and cookies and how to know where best to apply them and it seems to me you have really broken it down to my level. Thanks a lot. Maybe when i become as advanced as yourself i can be better able to handle using sessions without disrupting or tampering with server response time, page size and other important stuffs experts like yourself put into consideration for better website performance. Thanks once again.

    1. Hi @doubleprinceolami , thanks for the kind words! Glad we could helped you. Yes, there are optimization features you can add to your web app. It all depends on your needs.

      If you have the time please share our site to one of your friends, or subscribe https://www.codeofaninja.com/subscribe

  111. Fábio Avatar
    Fábio

    every files inside config?

    1. Hi @Fabio, no, usually database.php and config.php only.

  112. Felix, first of all, thank you for your feedback, I appreciate it!

    I did not purposely leave out the navigation.php file on this tutorial. As you can see in the comments, there were errors on that very file, which means it was previously included in this tutorial.

    Other version of the tutorial above has navigation.php file, see https://www.codeofaninja.com/2015/08/simple-php-mysql-shopping-cart-tutorial.html

    What happend was I accidentally leave out the navigation.php file when I updated the tutorial above. No one commented “navigation.php file & code is missing”. You are the only one who did it, so I thank you so much.

    Another note, I reply faster in the email, usually within 24 hours due to dozens of work emails I receive everyday. I still thank you for using our free tutorial above. Sorry for not replying to your comment instantly.

    I added the navigation.php file on section 5.2 above. In exchange of your effort to find a bug in this tutorial, I can send you the source code if you still need it. Send a request to my email [email protected]

    Again thank you for bringing this to my attention.

    1. Felix Wong Avatar
      Felix Wong

      Sorry Mike, I misunderstand you. I would like to withdraw my previous comment. I guess you are to busy and it not that easy to spot error in so many of your tutorials.

      1. Hi @disqus_oA8v8AP1xq, no worries, I understand! We all make mistakes. What’s more important is we try to make it right. 🙂

  113. Erfamae Fermo Avatar
    Erfamae Fermo

    why can’t i output the details of the product like the one in 9.0 please help

    1. Hi @erfamaefermo, would you share a screenshot of the error message?

  114. Fatal error: Call to undefined method Product::readByIds() in C:xampphtdocsphp-shopping-cart-using-sessions-level-1cart.php on line 51

  115. Fatal error: Call to undefined method Product::readByIds() in C:xampphtdocsphp-shopping-cart-using-sessions-level-1cart.php on line 51 ….can u please say ow to solve it

    1. Hi @madhav, the method readByIds() is in section 7.5, make sure you add that method first.

  116. Zero crack Avatar
    Zero crack

    Parse error: syntax error, unexpected T_PUBLIC in C:xampphtdocsphp-shopping-cart-using-sessions-level-1objectsproduct.php on line 52

    1. Hi @zero_crack, would you show us your product.php code? It looks like you missed a closing curly brace.

  117. 「 Knovosh 」 Avatar
    「 Knovosh 」

    Hello Im Knovosh, Im wondering if i can disable the image functions, when a user clicks the image the items details will appear how can i disable that …. I just want something when i click the image nothing will happen, based on your codes how can i do that badly needed

    1. Hi @Knovosh, I think you just need to remove the “a” tag that wraps the product item. It will remove the link so that it is not clickable.

  118. You’re welcome @Knovosh!

  119. Mr Krabs Avatar
    Mr Krabs

    Hello I do not know if the mistake comes from me or from them.
    I did everything after instruction and with me comes constantly the following error:
    Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in C:xampphtdocsshop_cart_sessions_1objectsproduct.php on line 52

    can you maybe help me because it is very important to me.
    Thank you.

    here is my code:
    https://mega.nz/#!GTww1ArZ!WpYMbGW8m4m5gaLv82wLr19eZhoxo4q6rLG9ZOGlCuk

    1. Hi @disqus_CyBYXb9HXE, I’m unable to replicate the issue. Would you paste your product.php code here? We are unable to see your code on the link you provided.

  120. Hi Dario, I’m unable to replicate the issue. Would you show us your code?

  121. @dariodiogo, it looks like your code is incomplete. Would you post your complete code and wrap it inside pre and code tags so it is formatted?

  122. Hi @lotlil, please don’t just copy our code. I suggest you understand how our code works. Based on the error, I think you misplaced a bracket.

  123. Hi @kevinpolistico, make sure your method is inside the class, before the last curly brace.

  124. Hi @krishnan_ramaswami, the screenshot does not look like our tutorial above. But the error says you have undefined variables in your read_orders_template.php, make sure you have values for those variables or use the isset() function to check if the values was set.

Leave a Reply

Your email address will not be published. Required fields are marked *