PHP Classes
PHP Classes
elePHPant
Icontem

How to Create a Simple PHP Shopping Cart Tutorial Step by Step Part 1: Add to Cart in PHP Example Source Code with AJAX, jQuery and MySQL - Demo Script using a Basket stored in Session Variables - Shopping Cart package blog

Recommend this page to a friend!
  All package blogs All package blogs   Shopping Cart Shopping Cart   Blog Shopping Cart package blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Simpl...  
  Post a comment Post a comment   See comments See comments (13)   Trackbacks (0)  

Author:

Updated on: 2017-04-15

Posted on:

Package: Shopping Cart

Many sites need to sell products online. There are many PHP e-commerce platforms but when you need something simple and easy, such platforms may be too much to adapt for your needs.

Read this article to learn how to implement a shopping cart that you can easily customize using PHP and a MySQL database to let your users view and pick the products they want to buy with fast user interface based on AJAX.




Contents

Shopping Cart PHP Tutorial: : Add to Cart in PHP Demo

Simple Add to Cart PHP Code

The AJAX PHP MySQL Database Structure

Simple Shopping Cart PHP Code for Listing Products

PHP Shopping Cart Using Session Variables

jQuery Shopping Cart Code

Shopping List PHP Code

Add to Cart in PHP Code with AJAX

Simple Add to Cart PHP Code

The Configuration File

The PHP Cart Class

Download the Simple Shopping Cart PHP Code


Shopping Cart PHP Tutorial: Add to Cart in PHP Demo

Shopping carts are a must for every site that needs to sell products online. This tutorial will show you how to make yourself one using PHP and AJAX.

You will learn how to list your products in a table, add a product to a shopping cart, remove an article from it, empty a shopping cart and how to checkout.

PHP Shopping Cart Code

In this part of the tutorial it is presented code for a complete PHP shopping cart application including the PHP scripts, JavaScript for sending AJAX requests using jQuery to process the shopping cart operations and database structure scripts to store the cart data in a MySQL database.

The AJAX PHP MySQL Database Structure

You do not need a database for managing the shopping cart itself, but because we want to list products for selling, we will need to retrieve the products from some place that it is flexible to update, like for instance a database. We are going to insert some initial product data in there for demonstration purposes.

Let us create one MySQL table named products. It has an ID, product name and a price. You can expand this table as you want. I am keeping it simple as this is not a tutorial about listing and creating products.

CREATE TABLE IF NOT EXISTS `products` (
 `id` int(9) NOT NULL,
 `product` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `price` float NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `products` ADD PRIMARY KEY (`id`);
ALTER TABLE `products` MODIFY `id` int(9) NOT NULL AUTO_INCREMENT;
INSERT INTO `products` (`id`, `product`, `price`) VALUES
(1, 'Product 1', 1.5),
(2, 'Product 2', 5),
(3, 'Product 3', 7.5),
(4, 'Product 4', 4.43);

I am inserting four products, named them Product 1 to Product 4, the prices are randomly set. Note that the price field is float, prices can be float values.

Simple Shopping Cart PHP Code for Listing Products

Now we will create a page which will list all the products with their prices, as well a link to add the product to the cart.

Let us create index.php script. It will contain a table dynamically generated using a loop through an array, that array will have the products list from the database. I will use a PHP class and will put in it a method which will query the products list and return them in the array.

PHP Shopping Cart Using Session Variables

Shopping carts need to be stored in some place to keep track of the products that the user picks. You can use any type of data storage. In this case I am using PHP sessions. They are easy to access, you can store arrays in them, and differently from database systems, you do not need to connect to them every time you need them, and they do not require the user of any query language. They are simply fast and easy to manipulate.

Create a file named index.php, and add this code in it:

<?php
 session_start();
 require_once("config.php");
 require_once("cart.php");
?>
<html xmlns = "http://www.w3.org/1999/xhtml">
 <head>
  <title>Example of AJAX Cart</title>
  <meta http-equiv = "Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script type="text/javascript" src="main.js"></script>
 </head>
 <body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0">
  <h1>Products list</h1>
  <?php
   $cart = new cart();
   $products = $cart->getProducts();
  ?>
  <table cellpadding="5" cellspacing="0" border="0">
   <tr>
    <td style="width: 200px"><b>Product</b></td>
    <td style="width: 300px" colspan="2"><b>Price</b></td>
   </tr>    <?php     foreach($products as $product) {    ?>     <tr>      <td><?php print HtmlSpecialChars($product->product); ?></td>      <td>$<?php print $product->price; ?></td>      <td style="text-align: center"><span style="cursor:pointer;" class="addToCart" data-id="<?php print $product->id; ?>">add to cart</span></td>     </tr>    <?php     }    ?>   </table>   <br /><a href="show-cart.php" title="go to cart">Go to cart</a>  </body> </html>

Product listing example

Here we could use a template engine to place the values of products in the page output to separate the script logic from the presentation logic. However, to simplify this tutorial we are using PHP statements in the middle of the HTML code just so you can easily see where everything goes.

In the first couple of lines before the HTML we activate the PHP sessions with the function session_start(), then included two files, config.php for configuration values, and cart.php which will be our class.

Next in the page head section we will need to include the jQuery library and main.js, a Javascript file that we will discuss later. Then before the table I am creating an instance to the cart class (we will discuss that later too) and calling getProducts method to get the products array back. For now we will discuss its details, just know that this method will return us an array with products ID, name and price.

Next with a foreach loop we are creating a table row for every product, listing the name, then price and a span having the product ID in data-id attribute. The span will be used to trigger a JavaScript function which will send the product ID by AJAX for the cart to add the product in the session.

Finally we show a link to the show-cart.php script where we will list the cart elements.

jQuery Shopping Cart Code

In both front end files we will be using two JavaScript files. One is the jQuery library which we are retrieving from a Content Delivery Network site (code.jquery.com). We are using jQuery as it is easy and comfortable. It has extensive AJAX support that will be used in main.js file.

Next let us create a simple JavaScript file named as main.js. It will have this code in it:

$( document ).ready( function() {
 $( "span.addToCart" ).on( "click", function() {
  var id = $(this).attr("data-id");
  $.ajax( {
   type: "GET",
   url: "ajax.php?id=" + id + "&action=add"
  })
  .done(function()
  {
   alert("Product have been added.");
  });
 });
});

In this file we are just registering one event handler, add to cart. It is used in the first front end file I already explained.

Note that we should register the event handlers after the document is fully loaded. This is important for the code to work correctly. We are attaching the event handler to an HTML element. If it is not loaded it will not work.

In index.php there is a span element in every row in the list of products with a class addToCart. We are attaching a click handler to every one, and assigning a function which will be called. The function will first get the ID of the product we clicked on, then we call an AJAX sending to it the ID and action add. The AJAX file will add the product to our cart, on finish we will trigger an alert to let us know that the product is in our cart.

By this JavaScript file we can add products to the cart interface.

Shopping List PHP Code

After adding products in the cart, you need to have a way to view them and show what is in the cart. We will use a script named show-cart.php which is very similar to the one before.

<?php
 session_start();
 require_once("config.php");
 require_once("cart.php");
?>
<html xmlns = "http://www.w3.org/1999/xhtml">
 <head>
  <title>Example of AJAX Cart</title>
  <meta http-equiv = "Content-Type" content="text/html; charset=utf-8" />
 </head>
 <body leftmargin="0" marginwidth="0" topmargin="0" marginheight="0">
  <h1>Show cart</h1>
  <?php
   $cart = new cart();
   $products = $cart->getCart();
  ?>
  <table cellpadding="5" cellspacing="0" border="0">
   <tr>
    <td style="width: 200px"><b>Product</b></td>
    <td style="width: 200px"><b>Count</b></td>
    <td style="width: 200px"><b>Total</b></td>
   </tr>    <?php     foreach($products as $product){    ?>     <tr>      <td><?php print HtmlSpecialChars($product->product); ?></td>      <td><?php print $product->count; ?></td>      <td>$<?php print $product->total; ?></td>     </tr>    <?php     }    ?>   </table>   <br /><a href="index.php" title="go back to products">Go back to products</a>  </body> </html>

As in index.php I am starting the session so we can access it. Then we are including the config file and the cart class.

In this script we will show the cart entries in a table, every row will have one product with its name. Also we will show the number of items of that product, as it can be bought more than one item of a product.

Of course one more information is required, it is the total price which is the price of a single item of a product multiplied with the number of items in the cart.

Add to Cart in PHP Code with AJAX

In the JavaScript file we used an AJAX request in the event handler. Actually we call one script named ajax.php, every time we gave it an action. Create a file named ajax.php and insert this code in it:

<?php
 session_start();
 require_once( "config.php" );
 require_once( "cart.php" );
 $cart = new cart();
 $action = strip_tags( $_GET["action"] );
 switch ($action) {
  case "add":
   $cart->addToCart();
   break;
 }
?>

Simple Add to Cart PHP Code

This is a PHP script that helps to interact with the cart class by AJAX, so I am starting session to be able to access the cart in the session. Then including the config file and the cart class. Now we create an instance of the class to access the methods we need.

With every call to this file we sent an action, so we get that action value and handle it in a switch case statement. In this case by providing add we call the addToCart method. It will add the sent product in the cart. Later we will discuss how to remove items and empty the cart.

The Configuration File

Before going on with the cart class, just create a script called config.php and add this code in it:

<?php 
 define("MYSQLSERVER","mysqlserver"); 
 define("MYSQLDB","mysqldb"); 
 define("MYSQLUSER","username"); 
 define("MYSQLPASSWORD","password"); 
?>

In this file we are defining the credentials of access to the database required by the database server so we can connect to it and pass authentication. These constants are used in the class. We are separating them into a single script to have easier and safer access to them.

The PHP Cart Class

Finally we are creating the cart class, here we have all the mothods we need for the cart to function. Create a file named as cart.php and copy this code in it.

To simplify this tutorial we have omitted error handling of eventual failures to connect to the database or execute queries, but robust applications should always implement error handling to provide good user experience and help the developer to debug errors when they happen.

<?php

class Cart {

 private $dbConnection;

 function __construct() {
  $this->dbConnection = new mysqli(MYSQLSERVER, MYSQLUSER, MYSQLPASSWORD, MYSQLDB);
 }

 function __destruct(){
  $this->dbConnection->close();
 }

 public function getProducts(){
  $arr = array();
  $dbConnection = $this->dbConnection;
  $dbConnection->query( "SET NAMES 'UTF8'" );
  $statement = $dbConnection->prepare( "select id, product, price from products order by product asc" );
  $statement->execute();
  $statement->bind_result( $id, $product, $price);
  while ( $statement->fetch() ) {
   $line = new stdClass;
   $line->id = $id; 
   $line->product = $product; 
   $line->price = $price;
   $arr[] = $line;
  }
  $statement->close();
  return $arr;
 }

 public function addToCart() {
  $id = intval($_GET["id"]);
  if($id > 0) {
   if($_SESSION['cart'] != "") {
    $cart = json_decode( $_SESSION['cart'], true);
    $found = false;
    for($i=0; $i<count($cart); $i++) {
     if($cart[$i][ "product" ] == $id){
      $cart[$i]["count"] = $cart[$i]["count"] + 1;
      $found = true;
      break;
     }
    }
    if(!$found) {
     $line = new stdClass;
     $line->product = $id; 
     $line->count = 1;
     $cart[] = $line;
    }
    $_SESSION['cart'] = json_encode($cart);
   } else {
    $line = new stdClass;
    $line->product = $id; 
    $line->count = 1;
    $cart[] = $line;
    $_SESSION['cart'] = json_encode($cart);
   }
  }
 }
 
 public function getCart(){ 
  $cartArray = array(); 
  if($_SESSION['cart'] != ""){ 
   $cart = json_decode($_SESSION['cart'], true); 
   for($i=0;$i<count($cart);$i++){ 
    $lines = $this->getProductData($cart[$i]["product"]); 
    $line = new stdClass; 
    $line->id = $cart[$i]["product"]; 
    $line->count = $cart[$i]["count"]; 
    $line->product = $lines->product; 
    $line->total = ($lines->price*$cart[$i]["count"]); 
    $cartArray[] = $line; 
   }
  }
  return $cartArray; 
 } 

 private function getProductData($id) {
  $dbConnection = $this->dbConnection;
  $dbConnection->query( "SET NAMES 'UTF8'" );
  $statement = $dbConnection->prepare( "select product, price from products where id = ? limit 1" );
  $statement->bind_param( 'i', $id);
  $statement->execute();
  $statement->bind_result( $product, $price);
  $statement->fetch();
  $line = new stdClass;
  $line->product = $product; 
  $line->price = $price;
  $statement->close();
  return $line;
 }
 }
?>
 

First let me explain the connection issue, as we will connect to the database more than once we are using a private member variable which will hold the connection. The connection will be opened on class creation by a constructor and closed by a destructor. I am so using the built-in __construct and __destruct methods to do that.

Next method is getProducts. We call that method in index.php file. We get the connection object, and make a query to the products table. The data is sorted in an array with a while loop using an empty generic class. The result is returned as an array.

In ajax.php we call addToCart method using the add action. We get the product ID sent via AJAX. If it is valid we test if the cart variable in session is empty. If it is empty we create a new entry, the product ID, count one and add it in session.

If the session variable is not empty, we loop through the cart array. If we find the product, we just increment the count variable. If it is not there we add it as a new element with count one. The changed array is returned back to the session.

By this we will make sure we do not have duplicates in the session, if product already exists we increase the count number by one, if not we add it there.

In show-cart.php we call the method getCart. It simply lists all cart products in an array. The problem we have here is in the cart we have only ID's and count of products, we do not have prices nor product names.

Here the getProductData private method gets handy. For every product in the cart we call it and get all the data needed to list in the array. getProductData method receives a product ID and returns its name and price.

Download the Simple Shopping Cart PHP Code

You can always use some of the e-commerce systems on-line, but they are too complicated and usually are not easy to customized. With this simple class you can customize your shopping cart and keep it simple and low weight.

The class package code is available right here for you to download the ZIP archive or install it using the Composer tool with instructions also on this page.

You can enhance it in many ways to make the class even better to address your needs like adding support for VAT and specify price currency.

In the next part we will how to do other stuff with the shopping cart like remove products or empty the cart.

If you liked this article or you have questions or suggestions, just post comment here.  If you have great suggestions to improve the package I may implement your ideas in the class in the future. Just let me know.




You need to be a registered user or login to post a comment

1,449,069 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:

FacebookGmail
HotmailStackOverflow
GitHubYahoo


Comments:

6. Android - Alex Solano (2016-10-29 03:10)
why it doesn't add in my device?... - 0 replies
Read the whole comment and replies

5. Add PayuMoney payment gateway - jaspal (2016-04-14 08:10)
Add PayuMoney payment gateway... - 0 replies
Read the whole comment and replies

4. AJAX shopping cart - Andy Burgess (2015-09-22 12:51)
Thanks and a couple of bugs... - 1 reply
Read the whole comment and replies

3. please add a total sum function... - mahdi ghas (2015-09-21 12:49)
please add a total sum function...... - 1 reply
Read the whole comment and replies

2. Thank you for posting this article. - Tim (2015-09-13 13:17)
product count or quantity.... - 2 replies
Read the whole comment and replies

1. Do not use float for price - Antoine Dubourg (2015-09-09 07:17)
Store prices as INTEGER in cents.... - 3 replies
Read the whole comment and replies



  Post a comment Post a comment   See comments See comments (13)   Trackbacks (0)  
  All package blogs All package blogs   Shopping Cart Shopping Cart   Blog Shopping Cart package blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Simpl...