PHP Shopping Cart Tutorial using MySQL database

simple-php-mysql-shopping-cart-tutorial

This PHP shopping cart tutorial using MySQL database will help you create a shopping cart system using PHP and MySQL. Previously, we learned how to create, read, update and delete database records on our PHP OOP CRUD tutorial. We will apply that knowledge by building a simple PHP shopping cart application.

Contents

Overview

In some cases, you might need to use cookies or sessions for storing products added to the cart. But this tutorial focuses on using the MySQL database to store products or items in the cart.

Pros & Cons

What are the pros of this approach? The user can view the products added to his cart on any computer or device as long as this user is logged in. The customer will be reminded of products in the cart so there is a higher chance of purchases in your online store.

What are the cons of this approach? If you have thousands of users, frequent access to the MySQL database might make your site slow. To prevent this, you will need to use a type of caching that is not covered in this tutorial.

Screenshots

PHP Shopping Cart Tutorial using MySQL database
PHP Shopping Cart Tutorial using MySQL database

Prepare the database

Database Design

Our database name is “php_shopping_cart”, and we will have three (3) tables.
simple-php-mysql-shopping-cart-tutorial database design

Create MySQL Tables

I’m using PhpMyAdmin to run the following queries on our “php_shopping_cart” database.

Create the products table. This table will store the products records.

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 product_images table. This table will hold images related to the product.

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 ;

Create cart_items table. This table will hold cart items of our user.

CREATE TABLE IF NOT EXISTS `cart_items` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `quantity` double NOT NULL,
  `user_id` int(11) 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 AUTO_INCREMENT=40 ;

Download sample data

The products and product_images table will not fully work without the sample products data and images in the “/uploads/images/” directory.

You’ll have to download the SQL and image files. Use the download link below. What will you get? A ZIP file with products_data.sql and 28 image files inside (1.30 MB).

Once downloaded, import the SQL file using PhpMyAdmin. Put the image files in the “/uploads/images/” directory.

Database connection file

Create the “config” folder and inside it, create the “database.php” file with the following code. This code will enable us to connect to our database and do database operations such as adding products to the cart or removing products from our shopping cart.

<?php
// used to get mysql database connection
class Database{

	// specify your own database credentials
	private $host = "localhost";
	private $db_name = "php_shopping_cart";
	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;
	}

}
?>

Prepare the user interface

We are about to create the layout files. Layout files contain reusable code that we can use on each of our web pages. This will help us have a consistent user interface.

Create header layout file

Create layout_head.php file and place the following code. We have some PHP code inside the title tags because we want the page title to be dynamic.

We’re using Boostrap to make our user interface look better. We also have some custom CSS.

<!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" />

    <!-- custom css for users -->
    <link href="libs/css/custom.css" rel="stylesheet" media="screen">

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

Create footer layout file

Create layout_foot.php file and place the following code. The script tags are needed by Bootstrap to function.

		</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.php

Create navigation.php file and put the following code inside. The navigation bar will contain links to the list of products and cart items.

<!-- 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 strpos($page_title, "Product")!==false ? "class='active'" : ""; ?>>
					<a href="products.php">Products</a>
				</li>

				<li <?php echo $page_title=="Cart" ? "class='active'" : ""; ?> >
					<a href="cart.php">
						<!--later, we'll put a PHP code here that will count items in the cart -->
						Cart <span class="badge" id="comparison-count">0</span>
					</a>
				</li>
			</ul>

		</div><!--/.nav-collapse -->

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

Add Custom CSS

Create the “libs” folder. And inside it, create a “css” folder. Create a custom.css file with the following code inside it. Custom CSS are needed to make our web page look better and more user-friendly.

.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;
}

Display products with pagination

Create products.php

Now we are going to start displaying products from the database. Create products.php with the following basic code. This is one instance where we use our layout files. At the top we specify our page title.

<?php
// set page title
$page_title="Products";

// page header html
include 'layout_head.php';

// contents will be here 

// layout footer code
include 'layout_foot.php';
?>

Include PHP Classes

Put this code after the opening “php” tag of products.php file. This code will enable us to connect to the database and then do database operations on specific tables.

// for database connection
include 'config/database.php';

// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// database connection request will be here

Create “product” object file

We’re going to create the “object” files. We have three objects: products, product images, and cart items.

Create “objects” folder. Inside it, create product.php file. Use the following code. This file will handle our queries on the products table.

<?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. This file will handle our queries on the product_images table.

<?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;
	}
}

Create “cart item” object file

Create cart_item.php file inside “objects” folder. This file will handle our queries on the cart_items table.

<?php
// 'cart item' object
class CartItem{

    // database connection and table name
    private $conn;
    private $table_name = "cart_items";

    // object properties
    public $id;
    public $product_id;
    public $quantity;
    public $user_id;
    public $created;
    public $modified;

	// constructor
    public function __construct($db){
        $this->conn = $db;
    }
}

Connect to the database

Open products.php file. Replace “// database connection request will be here” comment in products.php file with the following code.

This code will request a database connection and initialize the objects we created earlier.

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// action and pagination will be here

Initialize action and pagination

We’re going to initialize some variables using the following code.

The $action variable will be used to display custom prompt messages such as “Added to cart!” or “Removed from cart.”

The pagination variables will be used to control the pagination of products list.

Replace “// action and pagination will be here” comment with the following code.

// action for custom messages
$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

Request data from the database

This code will display the list of products from the database. If there are no products, it will display a “No products found.” message.

Replace “// contents will be here” comment in products.php with the following code.

// 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'>
    	<div class='alert alert-danger'>No products found.</div>
	</div>";
}

Add “read” method

We’re using the “read” and “count” methods of the product object but they do not exist yet. Open “objects/product.php” file.

Put the following “read” method. This code contains the actual query to retrieve the list of products from the products database.

// 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;
}

Add “count” method

Next, put the following count method. This code contains a query to count the total number of products in the database. It will be used for pagination.

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

Let’s create a template to display the products. Create “read_products_template.php" file. We will use the following code.

In this code, we loop through the list of products retrieved from the database so we can display them. On each loop of the product, we have a query to read and display a product image.

We default the user ID to “1” for now because this code is not yet integrated with a “user login” code like what we have in our PHP Login Script with Session tutorial.

We will also display the product’s name, price, category name, and the “Add to cart” button. If the item exists in our cart, we’ll display an “Update cart” button instead.

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

    // creating box
    echo "<div class='col-md-4 m-b-20px'>";

    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'>
					<img src='uploads/images/{$row_product_image['name']}' class='w-100-pct' />
				</div>";
    }

    // product name
    echo "<div class='product-name m-b-10px'>{$name}</div>
		</a>";

    // product price and category name
    echo "<div class='m-b-10px'>$" . number_format($price, 2, '.', ',') . "</div>";

    // add to cart button
    echo "<div class='m-b-10px'>";

    // cart item settings
    $cart_item->user_id = 1; // we default to a user with ID "1" for now
    $cart_item->product_id = $id;

    // if product was already added in the cart
    if ($cart_item->exists()) {
        echo "<a href='cart.php' class='btn btn-success w-100-pct'>Update Cart</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

We used the readFirst() method of the product_image object but it does not exist yet.

Open “objects/product_image.php” file. Put the following code. This code will read the first product image of a specific product.

// 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;
}

Add “exists()” method

We used the exists() method of the cart_items object but it does not exist yet.

Open /objects/cart_item.php file. Add the following code. This code will check if an item is already added to the cart or not.

// check if a cart item exists
public function exists(){

    // query to count existing cart item
    $query = "SELECT count(*) FROM " . $this->table_name . " WHERE product_id=:product_id AND user_id=:user_id";

    // prepare query statement
    $stmt = $this->conn->prepare( $query );

    // sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind category id variable
	$stmt->bindParam(":product_id", $this->product_id);
    $stmt->bindParam(":user_id", $this->user_id);

    // execute query
    $stmt->execute();

    // get row value
    $rows = $stmt->fetch(PDO::FETCH_NUM);

    // return
    if($rows[0]>0){
        return true;
    }

    return false;
}

Create pagination file

If we have a lot of products, it is ideal to paginate the product list so our web page will not be very long. The web page will also load faster which is great for the user experience.

Create paging.php file. Put the following code. This code will display the pagination buttons. It will have the first-page button, the page numbers, and then the last page button.

<?php
echo "<div class='col-md-12'>
<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.'>First Page</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>
            <a href='" . $page_url . "page={$total_pages}' title='Last page is {$total_pages}.'>
                Last Page
            </a>
        </li>";
}

echo "</ul>
</div>";

Output

Let’s run our product.php file on the browser. We should see the following output.

PHP shopping cart tutorial - output
PHP shopping cart tutorial using MySQL database – output

How to count items in the cart?

Display count in navigation bar

We will display the number of products the user has added to his cart. Open navigation.php file. Find the following lines of code.

<!--later, we'll put a PHP code here that will count items in the cart -->
Cart <span class="badge" id="comparison-count">0</span>

Replace that code with the following code. This code uses the count() method of the cart_item object to count the user’s products in his cart.

<a href="cart.php">
<?php
// count products in cart
$cart_item->user_id=1; // default to user with ID "1" for now
$cart_count=$cart_item->count();
?>
Cart <span class="badge" id="comparison-count"><?php echo $cart_count; ?></span>
</a>

Cart item count() method

The count() method of the cart_item object does not exist yet. Open /objects/cart_item.php file. Put the following code. This code queries the database for the number of products a specific user has added to his cart.

// count user's items in the cart
public function count()
{

    // query to count existing cart item
    $query = "SELECT count(*) FROM " . $this->table_name . " WHERE user_id=:user_id";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->user_id = htmlspecialchars(strip_tags($this->user_id));

    // bind category id variable
    $stmt->bindParam(":user_id", $this->user_id);

    // execute query
    $stmt->execute();

    // get row value
    $rows = $stmt->fetch(PDO::FETCH_NUM);

    // return
    return $rows[0];
}

Output

There are not many changes yet. But we know that the number “0” will increase once we added items to the cart.

How to add to cart?

Make “add to cart” button work

Let us make the “Add to Cart” button work. Create add_to_cart.php file. Put the following code. Our “Add to cart” buttons are linked to this file. There’s one parameter in the link which is the “product ID”. The default quantity is 1.

If the product exists in the cart, the user will be redirected to a page with a message saying the product already exists in the cart. Else, the system will create a cart_item record and redirect to a page where it says the product was added to the cart.

<?php
// parameters
$product_id = isset($_GET['id']) ? $_GET['id'] : "";
$quantity = 1;

// connect to database
include 'config/database.php';

// include object
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// set cart item values
$cart_item->user_id = 1; // we default to '1' because we do not have logged in user
$cart_item->product_id = $product_id;
$cart_item->quantity = $quantity;

// check if the item is in the cart, if it is, do not add
if ($cart_item->exists()) {
	// redirect to product list and tell the user it was added to cart
	header("Location: cart.php?action=exists");
}

// else, add the item to cart
else {
	// add to cart
	if ($cart_item->create()) {
		// redirect to product list and tell the user it was added to cart
		header("Location: cart.php?id={$product_id}&action=added");
	} else {
		header("Location: cart.php?id={$product_id}&action=unable_to_add");
	}
}

Add a create() method

We used the create() method of the cart_item object but it does not exist yet. Open /objects/cart_item.php file. Add the following code. This code contains a database query that will add the product as a cart item.

// create cart item record
function create()
{

	// to get times-tamp for 'created' field
	$this->created = date('Y-m-d H:i:s');

	// query to insert cart item record
	$query = "INSERT INTO
                " . $this->table_name . "
            SET
				product_id = :product_id,
				quantity = :quantity,
				user_id = :user_id,
				created = :created";

	// prepare query statement
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->product_id = htmlspecialchars(strip_tags($this->product_id));
	$this->quantity = htmlspecialchars(strip_tags($this->quantity));
	$this->user_id = htmlspecialchars(strip_tags($this->user_id));

	// bind values
	$stmt->bindParam(":product_id", $this->product_id);
	$stmt->bindParam(":quantity", $this->quantity);
	$stmt->bindParam(":user_id", $this->user_id);
	$stmt->bindParam(":created", $this->created);

	// execute query
	if ($stmt->execute()) {
		return true;
	}

	return false;
}

Create the cart page

We will now create the “cart” page. Create cart.php file. Put the following basic code. This page will list the products the user has added to the cart.

<?php
// connect to database
include 'config/database.php';

// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// set page title
$page_title="Cart";

// include page header html
include 'layout_head.php';

// contents will be here 

// layout footer
include 'layout_foot.php';
?>

Display message based on action

We’ll display messages on the cart page based on a given action. Put the following code after the “include ‘layout_head.php’;” code of cart.php file.

We have messages if the product was removed from the cart, the quantity was updated, the product already exists, and so on.

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

echo "<div class='col-md-12'>";
if ($action == 'removed') {
	echo "<div class='alert alert-info'>
			Product was removed from your cart!
		</div>";
} else if ($action == 'added') {
    echo "<div class='alert alert-info'>
			Product was added to cart!
		</div>";
} else if ($action == 'quantity_updated') {
	echo "<div class='alert alert-info'>
			Product quantity was updated!
		</div>";
} else if ($action == 'exists') {
	echo "<div class='alert alert-info'>
			Product already exists in your cart!
		</div>";
} else if ($action == 'cart_emptied') {
	echo "<div class='alert alert-info'>
			Cart was emptied.
		</div>";
} else if ($action == 'updated') {
	echo "<div class='alert alert-info'>
			Quantity was updated.
		</div>";
} else if ($action == 'unable_to_update') {
	echo "<div class='alert alert-danger'>
			Unable to update quantity.
		</div>";
}
echo "</div>";

Display products added to cart

We will now display the contents of the cart. Replace “// contents will be here” of the cart.php file with the following code.

This code below will show the product name, the update quantity input box and button, the delete from cart button, the price, and the total amount of products added to the cart.

If there are no products added to the cart yet, it will display a “No products found in your cart!” message

// $cart_count variable is initialized in navigation.php
if ($cart_count > 0) {

	$cart_item->user_id = "1";
	$stmt = $cart_item->read();

	$total = 0;
	$item_count = 0;

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

		$sub_total = $price * $quantity;

		echo "<div class='cart-row'>
			<div class='col-md-8'>";

		// product name
		echo "<div class='product-name m-b-10px'>
					<h4>{$name}</h4>
				</div>";

		// update quantity
		echo "<form class='update-quantity-form'>
					<div class='product-id' style='display:none;'>{$id}</div>
					<div class='input-group'>
						<input type='number' name='quantity' value='{$quantity}' class='form-control cart-quantity' min='1' />
							<span class='input-group-btn'>
							<button class='btn btn-default update-quantity' type='submit'>Update</button>
							</span>
					</div>
				</form>";

		// delete from cart
		echo "<a href='remove_from_cart.php?id={$id}' class='btn btn-default'>
					Delete
				</a>
			</div>

			<div class='col-md-4'>
				<h4>$" . number_format($price, 2, '.', ',') . "</h4>
			</div>
		</div>";

		$item_count += $quantity;
		$total += $sub_total;
	}

	echo "<div class='col-md-8'></div>
	<div class='col-md-4'>
		<div class='cart-row'>
			<h4 class='m-b-10px'>Total ({$item_count} items)</h4>
			<h4>$" . number_format($total, 2, '.', ',') . "</h4>
	        <a href='checkout.php' class='btn btn-success m-b-10px'>
	        	<span class='glyphicon glyphicon-shopping-cart'></span> Proceed to Checkout
	        </a>
		</div>
	</div>";
} else {
	echo "<div class='col-md-12'>
		<div class='alert alert-danger'>
			No products found in your cart!
		</div>
	</div>";
}

Put read() method in cart item object

We are using the read() method of the cart_item object in cart.php but it does not exist yet. Open /objects/cart_item.php file. Add the following code.

This code will request the list of items added to the cart by a specific user. It is using a MySQL LEFT JOIN keyword so we can get the product information such as the name and price.

// read items in the cart
public function read(){

	$query="SELECT p.id, p.name, p.price, ci.quantity, ci.quantity * p.price AS subtotal
			FROM " . $this->table_name . " ci
				LEFT JOIN products p
					ON ci.product_id = p.id
			WHERE ci.user_id=:user_id";

	// prepare query statement
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind value
	$stmt->bindParam(":user_id", $this->user_id, PDO::PARAM_INT);

	// execute query
	$stmt->execute();

	// return values
	return $stmt;
}

Output

Our cart page is not working! This is what it should look like.

How to update cart?

Update product quantity with JavaScript

We will update the product quantity with the help of JavaScript. We have the ‘update’ button on the cart.php file. When that button was clicked, it will trigger the following JavaScript code.

Open layout_foot.php file. Put the following code. This code will get the product ID and quantity entered by the user. It will pass those parameters using a redirect to the update_quantity.php file.

<script>
    $(document).ready(function() {
        // 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;
        });

        // image hover js will be here
    });
</script>

PHP script to update cart

Create the update_quantity.php file. Put the following code. This code will update the product quantity in the database. It will use the values of product_id, quantity, and user_id. It will redirect to the cart.php file to show a success or failure message.

<?php
// get the product id
$product_id = isset($_GET['id']) ? $_GET['id'] : 1;
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";

// make quantity a minimum of 1
$quantity=$quantity<=0 ? 1 : $quantity;

// connect to database
include 'config/database.php';

// include object
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// set cart item values
$cart_item->user_id=1; // we default to '1' because we do not have logged in user
$cart_item->product_id=$product_id;
$cart_item->quantity=$quantity;

// add to cart
if($cart_item->update()){
	// redirect to product list and tell the user it was added to cart
	header("Location: cart.php?action=updated");
}else{
	header("Location: cart.php?action=unable_to_update");
}

Update cart item in database

The update() method of the cart_item object does not exist yet. Open /objects/cart_item.php file. Add the following code. This code contains the MySQL update query that will update the product quantity in the cart_items table.

// create cart item record
function update(){

    // query to insert cart item record
    $query = "UPDATE " . $this->table_name . "
            SET quantity=:quantity
            WHERE product_id=:product_id AND user_id=:user_id";

    // prepare query statement
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->quantity=htmlspecialchars(strip_tags($this->quantity));
    $this->product_id=htmlspecialchars(strip_tags($this->product_id));
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

    // bind values
    $stmt->bindParam(":quantity", $this->quantity);
    $stmt->bindParam(":product_id", $this->product_id);
    $stmt->bindParam(":user_id", $this->user_id);

    // execute query
    if($stmt->execute()){
        return true;
    }

    return false;
}

How to remove product from cart?

In the cart.php file, we have the “Delete” button. When this button was clicked it will trigger the remove_from_cart.php file. This will remove a specific product from the cart.

Create remove_from_cart.php file. Put the following code. This code uses the values of product_id and user_id to delete the product from the cart. Once deleted, the user will be redirected to the cart page with a confirmation message.

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

// connect to database
include 'config/database.php';

// include object
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// remove cart item from database
$cart_item->user_id=1; // we default to '1' because we do not have logged in user
$cart_item->product_id=$product_id;
$cart_item->delete();

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

Put delete() method

The delete() method does not exist yet in the cart_item object. Open /objects/cart_item.php file. Add the following code. This code contains a DELETE MySQL query that will delete the product from the cart.

// remove cart item by user and product
public function delete(){

	// delete query
	$query = "DELETE FROM " . $this->table_name . " WHERE product_id=:product_id AND user_id=:user_id";
	$stmt = $this->conn->prepare($query);

	// sanitize
	$this->product_id=htmlspecialchars(strip_tags($this->product_id));
	$this->user_id=htmlspecialchars(strip_tags($this->user_id));

	// bind ids
	$stmt->bindParam(":product_id", $this->product_id);
	$stmt->bindParam(":user_id", $this->user_id);

	if($stmt->execute()){
		return true;
	}

    return false;
}

Create the checkout page

The checkout page looks like the cart page but the items cannot be updated or removed. It is just like the summary of orders with the total amount presented to the customer. It will also act as a confirmation page before the customer place the order.

Create checkout.php file. Put the following code. This code will request the cart data from the database. It will loop through the records to display the products added to the cart. It will also display the total cost of the order.

<?php
// connect to database
include 'config/database.php';

// include objects
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// set page title
$page_title = "Checkout";

// include page header html
include 'layout_head.php';

// $cart_count variable is initialized in navigation.php
if ($cart_count > 0) {

	$cart_item->user_id = "1";
	$stmt = $cart_item->read();

	$total = 0;
	$item_count = 0;

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

		$sub_total = $price * $quantity;

		echo "<div class='cart-row'>
			    <div class='col-md-8'>
                    <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'>
				<h4>$" . number_format($price, 2, '.', ',') . "</h4>
			</div>
		</div>";

		$item_count += $quantity;
		$total += $sub_total;
	}

	echo "<div class='col-md-12 text-align-center'>
		<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>

	        <a href='place_order.php' class='btn btn-lg btn-success m-b-10px'>
	        	<span class='glyphicon glyphicon-shopping-cart'></span> Place Order
	        </a>
		</div>
	</div>";
} else {
	echo "<div class='col-md-12'>
		<div class='alert alert-danger'>
			No products found in your cart!
		</div>
	</div>";
}

include 'layout_foot.php';

Create place_order.php

Create a place_order.php file. Put the following code. This code will show a “thank you” message. It will also remove all items in the cart so the customer can start with a new cart.

You can do a lot more with this file, for example, saving the order in your orders database. Unfortunately, we cannot cover that part in this tutorial for now.

<?php
// include classes
include_once "config/database.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$cart_item = new CartItem($db);

// remove all cart item by user, from database
$cart_item->user_id = 1; // we default to '1' because we do not have logged in user
$cart_item->deleteByUser();

// set page title
$page_title = "Thank You!";

// include page header HTML
include_once 'layout_head.php';

// tell the user order has been placed
echo "<div class='col-md-12'>
	<div class='alert alert-success'>
		<strong>Your order has been placed!</strong> Thank you very much!
	</div>
</div>";

// include page footer HTML
include_once 'layout_foot.php';

Delete all items in the cart

The deleteByUser() method does not exist yet in the cart_item object. Open /objects/cart_item.php file. Add the following code. This code contains a DELETE query that will delete all the products added to the cart of a specific user.

// remove cart items by user
public function deleteByUser(){
    // delete query
    $query = "DELETE FROM " . $this->table_name . " WHERE user_id=:user_id";
	$stmt = $this->conn->prepare($query);

	// sanitize
    $this->user_id=htmlspecialchars(strip_tags($this->user_id));

    // bind id
    $stmt->bindParam(":user_id", $this->user_id);

	if($stmt->execute()){
		return true;
	}

    return false;
}

Output

How to make the product page?

Product details page

Create product.php file. Put the following code. Once we completed the code on this product.php file, it will display the product details of a specific product.

<?php
// include classes
include_once "config/database.php";
include_once "objects/product.php";
include_once "objects/product_image.php";
include_once "objects/cart_item.php";

// get database connection
$database = new Database();
$db = $database->getConnection();

// initialize objects
$product = new Product($db);
$product_image = new ProductImage($db);
$cart_item = new CartItem($db);

// get ID of the product to be edited
$id = isset($_GET['id']) ? $_GET['id'] : die('ERROR: missing ID.');
$action = isset($_GET['action']) ? $_GET['action'] : "";

// set the id as product id property
$product->id = $id;

// to read single record product
$product->readOne();

// set page title
$page_title = $product->name;

// include page header HTML
include_once 'layout_head.php';

// content will be here

// include page footer HTML
include_once 'layout_foot.php';
?>

Read one product method

We are using the “readOne()” method of product object but it does not exist yet. Open the “objects” folder. Open product.php file. Put the following code. This code contains a SELECT query that will read product details for a specific product.

// used when reading product details
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

Let’s go back to the “product.php” file. Replace the “// content will be here” comment with the following code. This code will display the product images as thumbnails. When a thumbnail was hovered, it will display a larger version of that image.

// 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>";

// large image will be here

Read images related to product

The “readByProductId()” method does not exist yet in the product_image object. Open the “objects” folder. Open the “product_image.php” file. Put the following code. This code contains a SELECT query that will return the list of images related to the product.

// 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;
}

Display large image

We’re going to display a larger version of the product image using the following code. Replace the “// large image will be here” comment of the product.php file 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}'>
                <img src='{$source}' style='width:100%;' />
            </a>";
        $x++;
    }
} else {
    echo "No images.";
}
echo "</div>";

// product details will be here

Make image hover work

When the user hovers a thumbnail image, the larger version of the image must show up. We’re going to use JavaScript code to achieve this. Open the “layout_foot.php” file. Replace “// image hover js will be here” comment with the following code.

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

We will display the product price and description using the following code. Open product.php file. Replace the “// product details will be here” comment with the following code.

$page_description = htmlspecialchars_decode(htmlspecialchars_decode($product->description));

echo "<div class='col-md-5'>
		<h4 class='m-b-10px price-description'>$" . number_format($product->price, 2, '.', ',') . "</h4>
		<div class='m-b-10px'>
			{$page_description}
		</div>
	</div>";

// cart buttons will be here

Display a cart button

We will display the “Add to cart” button if the product is not yet added to the cart. Else, we will display the “Update cart” button. Open product.php file. Replace “// cart buttons will be here” comment with the following code.

echo "<div class='col-md-2'>";

// cart item settings
$cart_item->user_id = 1; // we default to a user with ID "1" for now
$cart_item->product_id = $id;

// if product was already added in the cart
if ($cart_item->exists()) {
	echo "<div class='m-b-10px'>This product is already in your cart.</div>
	<a href='cart.php' class='btn btn-success w-100-pct'>
		Update Cart
	</a>";
}

// if product was not added to the cart yet
else {
	echo "<a href='add_to_cart.php?id={$id}' class='btn btn-primary w-100-pct'>Add to Cart</a>";
}

echo "</div>";

Ouput

What People Say?

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

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

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

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

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

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

Download source code

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

There’s a small fee in getting the complete source code, it is small compared to the:

  • Value or skill upgrade it can bring you.
  • The income you can get from your website project or business.
  • Precious time you will save.
  • Expert advice and support (if you have any questions related to the source code)
Source code featuresLevel 1Level 2
List all products from the MySQL databaseYESYES
Pagination of products listYESYES
Add to cart buttonYESYES
Remove from cart buttonYESYES
Show message if a product was added to the cartYESYES
Show message if a product was removed to cartYESYES
Navigation bar highlights which page is selectedYESYES
Cart menu shows the number of products added to the cartYESYES
Show message if no products foundYESYES
Show message if no product found in the cartYESYES
Bootstrap enabled UIYESYES
Cart page that lists all products added to cartYESYES
Compute the total cost of all products added to the cartYESYES
Update cart with the desired quantityYESYES
Single product view with add to cart buttonYESYES
Check out button with cart iconYESYES
The navigation bar has a drop-down of product categoriesNOYES
The selected category is highlighted in the drop-downNOYES
Categories are retrieved from the databaseNOYES
Show products by categoryNOYES
List products under a category with paginationNOYES
Search productNOYES
Search results with paginationNOYES
Search box located on the navigation barNOYES
Search box requires search term before clicking the search buttonNOYES
Quantity text box required to be a number, have a minimum value of 1NOYES
Quantity text has a negative value not allowedNOYES
Remember the page number where the user clicked the “Add to cart” buttonNOYES
Well formatted money valueNOYES
One-click empty cart buttonNOYES
Free support and code updates1 year1 year

Need more features?

We have two more source codes related to our tutorial above.

PHP Shopping Cart Module. It has several features you will enjoy learning. Some examples: how to handle the users, shopping cart, and ordering using the PHP & MySQL technology. Click here to learn more.

PHP Shopping Cart SYSTEM. Many of you requested this source code. You needed a shopping cart system with user management (admin/merchant and customer), product management, category management, order management, and more features. Click here to learn more.

What’s Next?

We made another version of this tutorial. We used PHP session variables to store products added to the cart. This is a great tutorial about PHP sessions.

You can find the tutorial here: PHP and MySQL Shopping Cart Tutorial – Using SESSIONS To Store Cart Data

Thank you for studying our tutorial about the simple shopping cart tutorial using MySQL database!

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

80 comments

  1. Hi @Gabriel, thanks for the kind words! I’m unable to determine line 39 and 40 of your code. Would you tell us which section is it on our tutorial above? I’ll update the tutorial with your fixes.

  2. Hi @zanetadziura, thanks for sending your concern and sorry for the late reply. It’s been a crazy month for me. Anyway, it looks like you did not declare your $page_title in your PHP file. Would you send your code to my email [email protected]?

  3. Hi @disqus_j9XmuSg1Vc, would you tell us the specific reason why do you think the generation of HTML from PHP is a concern? Our project above is very small so I don’t think a template system is needed.

    Also, would you further explain “at the very least use standard html with php echoed only for placeholders”? Please give us examples based on our tutorial above about what we should’ve done instead.

    Thank you!

    1. First, echoing PHP is not very readable and not easily maintained. Secondly, you lose any syntax highlighting in your HTML. Notice that all your HTML is blue. That’s because your editor just sees anything echoed as a string and not HTML. If you forgot to close a tag your editor will not help you since it just sees what’s inside the echo statement as a string.

      As an example I would not echo everything, just variables like below:

      Product category:
      category_name ?>

      You did this in one of your files, cart.php, and notice above that the HTML has syntax highlighting?

      1. Hi @disqus_j9XmuSg1Vc, thanks for explaining your side! I respect your view if you think syntax highlighting is a big concern for you.

        For me, it is not a concern and the code above is my own style. In my view, the code is very readable and easier to debug if I echo the HTML per line.

        About syntax highlighting above, it is not my editor, it is just a highlighting plugin for this site that may not be doing a good job for you.

        Syntax highlight in my Atom or Notepad++ editor works great for me.

        I’ve been coding PHP for several years, made successful web apps with my coding style. I just think our code above is not for you so I suggest you look for a tutorial somewhere else where it fits your style.

        Thanks for your time!

      2. There were some things I really liked about the tutorial especially the step instructions. I will be using some of the ideas, but using templates, object oriented php and more separation of concerns.

      3. Those concepts can be useful for big web apps. Our tutorial above is small in scope. We will appreciate if you send us resources that can be useful to improve our tutorial above. Thanks again for your contribution to this page @disqus_j9XmuSg1Vc!

  4. I downloaded the bootstrap-3.3.7 from the link mentioned above in the tutorial but there is no file bootstrap/docs-assets/js/holder.js (as well as in /docs/assets/js/holder.js )
    Could you please advice what I’m doing wrong?

  5. And I have 1 more problem which is weird to me that when I am on products page I does not show products, only when I am using mobile resolution..

  6. Hello, first I want to say that this is great tutorial :) I managed to solve all the problems by far but I cannot move from this one.

    Notice: Undefined variable: id in C:xampphtdocscart_projectlayout_foot.php on line 75
    code -> $cart_item->product_id=$id;
    Notice: Undefined variable: id in C:xampphtdocscart_projecttlayout_foot.php on line 90
    code -> echo “{$id}”;

    thank you for quick respond, Lukas

    1. Hi @Lukas, thanks for the kind words about our tutorial. Sorry for the late reply, I was on vacation. Would you share your solution?

      About the error message, it looks like the variable $id is not initialized in your layout_head.php or whichever file you are using the $id variable before the layout_foot.php

  7. I’m facing 2 problem about the tutorial,
    1. Step 10.4, where’s the “include_once ‘layout_head.php’;” mentioned? It said that it’s from the previous part but I can’t find it in 10.3.
    2. Step 10.10, where’s should i put those code?
    I’m totally new to php and database.

  8. Where’s the “include_once ‘layout_head.php’;” mentioned in step 10.4?
    It said it’s in the previous part, but I can’t found it in step10.3 .
    Isn’t anything that I missunderstood about this step in tutorial?

  9. Woah, you completed our PHP API tutorial for free and have some nice words about it, and now you comment like this? If you have a problem with our tutorial, you can just immediately ask, we’ll answer as fast as we can, or you learn somewhere else. This will save you a lot of time. Many people completed this tutorial successfully, maybe the problem is at your end.

  10. Hi @disqus_66AbeWJ4ff, on your products.php, it looks like you did not include and instantiate the ‘product’ object before including the navigation.php file.

    The tutorial above does not need the users table.

  11. Again on the file structure there is no cart_item but following the tutorial there is cart_item inside the objects folder.

  12. Hi mike i followed this tutorial but after all thesteps i got this error kindly help
    Parse error: syntax error, unexpected T_PUBLIC in C:xampphtdocscartobjectsproduct.php on line 51

      1. // 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];

        }

      2. // 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];

        }

      3. I mean, the line 51 only of your code, not the whole function. That’s where your error comes from. It is a syntax error meaning there you might be missing a semicolon or something else.

      4. Thanks I later found out what was missing in the code i placed the functions out of the curly brace

  13. Mike,
    When purchasing the access to level 2 and 3, do you include a step by step tutorial as well or just the code?

    1. Hello @disqus_61IO91MD3h , LEVEL 2 & 3 does not have step by step tutorial. That is why we highly recommend learning the LEVEL 1 source code first so you can understand LEVEL 2, then LEVEL 3 easier.

      But if download the LEVEL 2 & 3 source codes, and you have any questions, you can just email me and I’ll answer you. My email address is [email protected]

    1. Hello @Liem, I highly recommend doing it because you’ll learn how it was made from smaller code base to a bigger code base. If you think you can take on the LEVEL 3 source code directly, you can go ahead as well.

  14. Hi Mike, just been going through some of your tutorials and they’re great! Very nice code man. I wish i had the funds to get the extra levels. Hopefully soon!
    Im playing around with this tutorial at the moment and im trying to understand the jquery you have put in the footer. What exactly is happening here?

  15. hi mike..would u pls help me in this..i need to pass the value of the quantity entered by the user to the cart.php using $_get or $_post or $_session and update the value.. but i tried them all no one of them worked with me.. here are the codes for each page.
    1- products.php

    <?php
    $page_title="Products";

    include 'layout_head.php';

    $conn = oci_connect("system", "123", "//localhost/xe");

    // to prevent undefined index notice

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

    $product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "1";

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

    if($action=='added'){

    echo "”;

    echo “{$name} was added to your cart!”;

    echo “”;

    }

    if($action==’exists’){

    echo “”;

    echo “{$name} already exists in your cart!”;

    echo “”;

    }
    $query = “SELECT ID,NAME,PRICE FROM PRODUCT ORDER BY NAME “;

    $result = oci_parse($conn,$query);

    oci_execute ($result,OCI_DEFAULT);

    if($result){

    //start table

    echo “”;
    // our table heading

    echo “”;

    echo “Product Name”;

    echo “Price (RM)”;

    echo “Quantity”;

    echo “Action”;

    echo “”;

    while($row = oci_fetch_array($result,OCI_BOTH)) {

    //creating new table row per record

    echo “”;

    echo “”;

    echo “{$row[“ID”]}”;

    echo “{$row[“NAME”]}”;

    echo “”;

    echo “{$row[“PRICE”]}</”;

    echo “”;

    echo “”;

    echo “”;

    echo “”;

    echo ““;

    echo ” Add to cart”;

    echo ““;

    echo “”;

    echo “”;

    }

    echo “”;

    }

    // tell the user if there’s no products in the database

    else{

    echo “No products found.”;

    }
    include ‘layout_foot.php’;

    ?>

    2- cart.php

    <?php

    $page_title="Cart";

    include 'layout_head.php';

    $conn = oci_connect("system", "123", "//localhost/xe");

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

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

    //$cart_items = isset($_GET['cart_items']) ? $_GET['cart_items'] : "";

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

    if($action=='removed'){

    echo "”;

    echo “{$name} was removed from your cart!”;

    echo “”;

    }

    else if($action==’quantity_updated’){

    echo “”;

    echo “{$name} quantity was updated!”;

    echo “”;

    }

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

    // get the product ids

    $ids = “”;

    foreach($_SESSION[‘cart_items’] as $id=>$value){

    $ids = $ids .”‘”. $id . “‘” .”,”;

    }

    // remove the last comma

    $ids = rtrim($ids, ‘,’);

    //start table

    echo “”;

    // our table heading

    echo “”;

    echo “Product Name”;

    echo “Price (USD)”;

    echo “Quantity”;

    echo “Sub Total”;

    echo “Action”;

    echo “”;

    $query = “SELECT id, name, price FROM product WHERE id IN (“.$ids.”) ORDER BY NAME”;

    $result = oci_parse($conn,$query);

    oci_execute($result,OCI_DEFAULT);

    $subtotal = 0;

    $total_price=0;

    while($row = oci_fetch_array($result,OCI_BOTH)){

    echo “”;

    echo “{$row[“NAME”]}”;

    echo “{$row[“PRICE”]}”;

    echo “”;

    echo “”;

    echo “”;

    echo “”;

    echo “Update”;

    echo “”;

    echo “”;

    echo “”;

    $subtotal = $quantity * $row[“PRICE”];

    echo “{$subtotal}”;

    echo “”;

    echo ““;

    echo ” Remove from cart”;

    echo ““;

    echo “”;

    echo “”;

    $total_price+=$row[“PRICE”];

    }

    echo “”;

    echo “Total“;

    echo “{$total_price}”;

    echo “”;

    echo ““;

    echo ” Checkout”;

    echo ““;

    echo “”;

    echo “”;

    echo “”;

    }

    else{

    echo “”;

    echo “No products found in your cart!”;

    echo “”;

    }

    include ‘layout_foot.php’;

    ?>

    thanks in advance.. @mike dalisay

  16. hey Add to cart button is not working… please teach me how it can be fix with easy steps… i’m new to php.

  17. People that are saying the ‘add to cart’ button is not working might be ignoring that they have to add the jquery and bootstrap files themselves. Download the files and change the script lines in ‘layout_foot.php’ under both jQuery Library and bootstrap javascript. You can find the files online.

  18. Mike, once again thanks for these great tutorials. I have followed both your SESSION Tutorial and your MySQL tutorial. The MYSQL one saves data to a database so that the user will always have the items stored in the cart. However, how would I implement this to have a log in system so that multiple users can save to their cart and then log out without loosing their cart data. For example, I need a system that allows users to log in add 2 items to the cart, log out and then log back in and the items will still be there.

    Please help as I am really struggling!!

    Thanks

    1. Hello @disqus_2s7yg8qBz7, well, the idea is you need to create a small user management system, like user registration or creation on an admin section. When the created user is logged in, you will save his user ID in a PHP session or cookie so that it will be accessible on any page of your site. Once he uses the cart feature, you will save each cart record with that user ID. That way, when he logs out and tried to log in again, his cart items will stay. Your query will look like “select * from cart_items where user_id=?”;

      You have another option. Our LEVEL 3 source code above (section 5.3) can do the features you need. How about you download that source code instead? You will learn a lot from that source code for sure. In case you had any related questions or need clarification or more explanation on something, I will answer to help you.

      1. The point where I am struggling is that the login system already exists. I am trying to intergrate the shop application with the log in system. Also, how do I retrieve the user id and store in a session? Do I need to query the database?

      2. Hi @ninjazhai , I have modified the system to update the cart for a specific user and save to a database. There is one thing that I cannot understand though, which is that the buttons on the product page stay as added for all the users even if that item is not stored in the cart. For example, I log in with user 1, add three items to the cart and then log out. I then log in with user two and although he has no items in his cart, the page buttons still say ‘Added’

      3. Did you make any changes in the products.php? It should have the query for each product (or join query) that checks if a certain user added that product. That way, system will determine if a product is ‘added’ or not.

      4. Mike, I have created the login system and users can now log in and add items to their basket. The only problem I have encountered is that if one user adds two items to his basket and then logs out and user 2 logs in, the page buttons still display as added when they have only been added for one person. It should not do this because user 2 does not have any items. Any ideas how to fix this?

  19. Hello @ronneilheredia, we are unable to replicate your issue, it works at our end just as seen in the screenshots. It is very hard to debug if you don’t share your test URL or code and we don’t see any error messages.

  20. hello @mike… i follow all the code above and the problems is add to cart is not working… this is for my project in OOP subject.. I’m a 2nd year now taking up BSICT

  21. Hi @kohmunchun, are you sure you followed step 4? This line:

    [pre]

    $page_title=&quot;Products&quot;;

    [/pre]

    must prevent the Notice: Undefined variable: page_title issue.

    Also please make sure you are correctly connected to your database via config/database.php

  22. Notice: Undefined variable: page_title in C:xampphtdocsmypagesconfignavigation.php on line 17

    > Products

    Notice: Undefined variable: page_title in C:xampphtdocsmypagesconfignavigation.php on line 20

    >

    Notice: Undefined variable: con in C:xampphtdocsmypagesconfignavigation.php on line 27

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

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top