Creating Simple Shopping Cart with PHP

Shopping Cart is very important part of any online store, it not only allows user to accumulate list of items for final purchase, but also calculates total amount of all the products. Since my last article on PayPal Express Checkout with PHP, I have received few emails asking how to create a simple PHP session based shopping cart for the website. So, keeping that in mind, today we are going to create a shopping cart, which is simple and can be integrated easily in any website that runs on PHP.

shopping-cart

I have created 4 files for our shopping cart:

  1. Config.php (MySql credentials)
  2. Index.php (list of product information from database)
  3. Cart_update.php (Updates cart items and redirects back to products list page)
  4. View_cart.php (Product summery view before the payment)

Products List

All our products information should be stored in MySql table, for that we can create a table named “products” using MySql statement below, you can insert the products details manually using PhpMyAdmin, OR use MySql file in downloadable zip, which you can import in PhpMyAdmin.

1
2
3
4
5
6
7
8
9
10
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_code` varchar(60) NOT NULL,
  `product_name` varchar(60) NOT NULL,
  `product_desc` tinytext NOT NULL,
  `product_img_name` varchar(60) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_code` (`product_code`)
) AUTO_INCREMENT=1 ;

Once you have database table, you can create a list of products, similar to picture below:
Product Details

Configuration

Purpose of the config file is to store various information we need for our script. Here we are just going to enter MySql authentication details to access database table. Just enter the MySql details in the configuration file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$currency = '&#8377; '; //Currency Character or code

$db_username = 'root';
$db_password = '';
$db_name = 'test';
$db_host = 'localhost';

$shipping_cost      = 1.50; //shipping cost
$taxes              = array( //List your Taxes percent here.
                            'VAT' => 12,
                            'Service Tax' => 5
                            );                     
//connect to MySql                     
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);                       
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
?>

Product List (Index.php)

This will be the page where you want to display the list the products you want to sell. If you have lots of products, it is better to group them in pages using some sort of pagination. And on the right side of the page will be our shopping-cart box, which will keep track of items user going to purchase later.

Since we are working with sessions, we must activate PHP session in our script by including session_start() on top of the code, then we can start writing other codes or include file:

1
2
3
4
<?php
session_start();
include_once("config.php");
?>

Listing Products from Database

We will basically fetch the records from database and display them on the page. We will also create a HTML form with Add to Cart button. Important part here is the HTML form, notice the hidden input values? Each item contains a form with these hidden values, product code and the return URL, which we will send to cart_update.php using POST method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<div class="products">
<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);

$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img_name, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
    <li class="product">
    <form method="post" action="cart_update.php">
    <div class="product-content"><h3>{$obj->product_name}</h3>
    <div class="product-thumb"><img src="images/{$obj->product_img_name}"></div>
    <div class="product-desc">{$obj->product_desc}</div>
    <div class="product-info">
    Price {$currency}{$obj->price}
   
    <fieldset>
   
    <label>
        <span>Color</span>
        <select name="product_color">
        <option value="Black">Black</option>
        <option value="Silver">Silver</option>
        </select>
    </label>
   
    <label>
        <span>Quantity</span>
        <input type="text" size="2" maxlength="2" name="product_qty" value="1" />
    </label>
   
    </fieldset>
    <input type="hidden" name="product_code" value="{$obj->product_code}" />
    <input type="hidden" name="type" value="add" />
    <input type="hidden" name="return_url" value="{$current_url}" />
    <div align="center"><button type="submit" class="add_to_cart">Add</button></div>
    </div></div>
    </form>
    </li>
EOT
;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
</div>

Shopping Cart Box

On the right side of the page we will display small shopping cart box to keep track of user items. The main task of the shopping-cart is to look for session variable called $_SESSION[“cart_products”], which holds the collection of user items in an array, and then retrieve and display its content in the box.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
    echo '<div class="cart-view-table-front" id="view-cart">';
    echo '<h3>Your Shopping Cart</h3>';
    echo '<form method="post" action="cart_update.php">';
    echo '<table width="100%"  cellpadding="6" cellspacing="0">';
    echo '<tbody>';

    $total =0;
    $b = 0;
    foreach ($_SESSION["cart_products"] as $cart_itm)
    {
        $product_name = $cart_itm["product_name"];
        $product_qty = $cart_itm["product_qty"];
        $product_price = $cart_itm["product_price"];
        $product_code = $cart_itm["product_code"];
        $product_color = $cart_itm["product_color"];
        $bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
        echo '<tr class="'.$bg_color.'">';
        echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
        echo '<td>'.$product_name.'</td>';
        echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
        echo '</tr>';
        $subtotal = ($product_price * $product_qty);
        $total = ($total + $subtotal);
    }
    echo '<td colspan="4">';
    echo '<button type="submit">Update</button><a href="view_cart.php" class="button">Checkout</a>';
    echo '</td>';
    echo '</tbody>';
    echo '</table>';
   
    $current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
    echo '</form>';
    echo '</div>';

}
?>
</div>

Updating Cart

The role of the Cart_update.php is to add and remove items in the shopping cart. When user clicks “Add to Cart” button, the form sends some hidden values such as product code and quantity to Cart_update.php using POST method, which we will use to retrieve product info from the database verifying the existence of the product, and then we create or update $_SESSION[“cart_products”] with new array variables. Removing item works similar way, please go though comment lines below, most of the code is self explanatory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
session_start(); //start session
include_once("config.php"); //include config file

//add product to session or create new one
if(isset($_POST["type"]) && $_POST["type"]=='add' && $_POST["product_qty"]>0)
{
    foreach($_POST as $key => $value){ //add all post vars to new_product array
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING);
    }
    //remove unecessary vars
    unset($new_product['type']);
    unset($new_product['return_url']);
   
    //we need to get product name and price from database.
    $statement = $mysqli->prepare("SELECT product_name, price FROM products WHERE product_code=? LIMIT 1");
    $statement->bind_param('s', $new_product['product_code']);
    $statement->execute();
    $statement->bind_result($product_name, $price);
   
    while($statement->fetch()){
       
        //fetch product name, price from db and add to new_product array
        $new_product["product_name"] = $product_name;
        $new_product["product_price"] = $price;
       
        if(isset($_SESSION["cart_products"])){  //if session var already exist
            if(isset($_SESSION["cart_products"][$new_product['product_code']])) //check item exist in products array
            {
                unset($_SESSION["cart_products"][$new_product['product_code']]); //unset old array item
            }          
        }
        $_SESSION["cart_products"][$new_product['product_code']] = $new_product; //update or create product session with new item  
    }
}


//update or remove items
if(isset($_POST["product_qty"]) || isset($_POST["remove_code"]))
{
    //update item quantity in product session
    if(isset($_POST["product_qty"]) && is_array($_POST["product_qty"])){
        foreach($_POST["product_qty"] as $key => $value){
            if(is_numeric($value)){
                $_SESSION["cart_products"][$key]["product_qty"] = $value;
            }
        }
    }
    //remove an item from product session
    if(isset($_POST["remove_code"]) && is_array($_POST["remove_code"])){
        foreach($_POST["remove_code"] as $key){
            unset($_SESSION["cart_products"][$key]);
        }  
    }
}

//back to return url
$return_url = (isset($_POST["return_url"]))?urldecode($_POST["return_url"]):''; //return url
header('Location:'.$return_url);

View Item Summary

Now we have everything ready, its time for final page where user can view their products and proceed to payment. It’s good idea to add taxes, shipping and transaction fees along with total amount in this page for the users to see. You can generate any type of data here for the Payment gateway, most Payment gateway prefer HTML form, so I have create some hidden input fields, you can modify them to suit your needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%"  cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
  <tbody>
    <?php
    if(isset($_SESSION["cart_products"])) //check session var
    {
        $total = 0; //set initial total value
        $b = 0; //var for zebra stripe table
        foreach ($_SESSION["cart_products"] as $cart_itm)
        {
            //set variables to use in content below
            $product_name = $cart_itm["product_name"];
            $product_qty = $cart_itm["product_qty"];
            $product_price = $cart_itm["product_price"];
            $product_code = $cart_itm["product_code"];
            $product_color = $cart_itm["product_color"];
            $subtotal = ($product_price * $product_qty); //calculate Price x Qty
           
            $bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
            echo '<tr class="'.$bg_color.'">';
            echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
            echo '<td>'.$product_name.'</td>';
            echo '<td>'.$currency.$product_price.'</td>';
            echo '<td>'.$currency.$subtotal.'</td>';
            echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
            echo '</tr>';
            $total = ($total + $subtotal); //add subtotal to total var
        }
       
        $grand_total = $total + $shipping_cost; //grand total including shipping cost
        foreach($taxes as $key => $value){ //list and calculate all taxes in array
                $tax_amount     = round($total * ($value / 100));
                $tax_item[$key] = $tax_amount;
                $grand_total    = $grand_total + $tax_amount;  //add tax val to grand total
        }
       
        $list_tax       = '';
        foreach($tax_item as $key => $value){ //List all taxes
            $list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
        }
        $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
    }
    ?>
    <tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
    <tr><td colspan="5"><a href="index.php" class="button">Add More Items</a><button type="submit">Update</button></td></tr>
  </tbody>
</table>
<input type="hidden" name="return_url" value="<?php
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>

Continue to PHP Shopping Cart to PayPal Payment Gateway.

Download Demo

1
  • Saran

  • Article written by Saran. Saran Chamling loves the web technology, and enjoys designing, exploring and writing about it @sanwebe.com. You can find him at Twitter, Google or Facebook.

350 Comments Add Comment

  • hi, when “chech-out” is clicked, the products that you bought will be displayed right?
    i also wanted to display the products picture, how to do it?
    any one? please answer..

     Reply
    • try using the following code in the ‘view_cart.php’ file:

      <?php
      session_start();
      include_once("config.php");
      if(isset($_SESSION["products"]))
      {
      $total = 0;
      echo '’;
      echo ”;
      $cart_items = 0;
      foreach ($_SESSION[“products”] as $cart_itm)
      {
      $product_code = $cart_itm[“code”];
      $results = $mysqli->query(“SELECT product_name,product_desc, price, product_img_name FROM products WHERE product_code=’$product_code’ LIMIT 1″);
      $obj = $results->fetch_object();

      echo ”;
      echo ‘product_img_name.'”>’;
      echo ‘ב;
      echo ”.$currency.$obj->price.”;
      echo ”;
      echo ”.$obj->product_name.’ (Code :’.$product_code.’) ‘;
      echo ‘Qty : ‘.$cart_itm[“qty”].”;
      echo ”.$obj->product_desc.”;
      echo ”;
      echo ”;
      $subtotal = ($cart_itm[“price”]*$cart_itm[“qty”]);
      $total = ($total + $subtotal);

      echo ‘product_name.'” />’;
      echo ”;
      echo ‘product_desc.'” />’;
      echo ”;
      $cart_items ++;

      }
      echo ”;
      echo ”;
      echo ‘Total : ‘.$currency.$total.’ ‘;
      echo ”;
      echo ”;

      }else{
      echo ‘Your Cart is empty’;
      }
      ?>

    • in the view_cart.php file:

      replace sql query with: SELECT product_name,product_desc, price, product_img_name FROM products WHERE product_code=’$product_code’ LIMIT 1

      then add img src=”images/’.$obj->product_img_name.'” within some div tags in the foreach loop.

    • echo ‘product_img_name.'”>’;

    • remove my previous code. tq

    • When submit..how to make it go to database order?

  • ARGH!! Errors on index.php page what is wrong help please!

    1
    2
    3
    Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/content/10/12063410/html/fastburger/bailliestest/shoppingcart/index.php:6) in /home/content/10/12063410/html/fastburger/bailliestest/shoppingcart/index.php on line 7

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/content/10/12063410/html/fastburger/bailliestest/shoppingcart/index.php:6) in /home/content/10/12063410/html/fastburger/bailliestest/shoppingcart/index.php on line 7
     Reply
  • Hello

    Love this tutorial!
    However, i’ve got a small procblem and i’m not sure what to do as i’m new to all this.

    Heres my error:

    Notice: Undefined variable: mysqli in /home/11022689/www/index.php on line 11 Fatal error: Call to a member function query() on a non-object in /home/11022689/www/index.php on line 11

    The code is exactly the same as the one above….
    Can you help me?

    Thank you!

     Reply
  • Thanks for this tutorial! It helped me really to realize a similar project using ajax.
    But i have one problem: if you have many products on a page…scroll down to a product and click “add item to basket” the page allways scrolls to the top of the body. How can i stop scrolling to top after click on the button? This is a similar post: http://stackoverflow.com/questions/5449833/stop-scrolling-to-top-after-ajax-request
    If i try this with JavaScript the item will not be added to the basket :(

     Reply
  • Hello,
    How could I include the items present in the view_cart.php file, after the user selected to check-out, in a form to email? I basically know how to create the form, I just don’t know how to include these items.
    Thanks a lot, great tutorial btw, probably the best one I’ve found on the internet.
    -janos

     Reply
  • Say for after checkout I would like to store both the order and customer name, address till the order has been dispatched then how to do it. How to store both the order and customer details in a table (say if a new table order is created in the database)

     Reply
  • what if i want to save the information of cart in database? any possible codes? im confuse..

     Reply
    • Yes it is possible, I am sharing my code with you, hope you’ll able to manipulate it according to your desire. On the process.php, follow this code:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      foreach ($_POST['item_name'] as $key=>$itmname)
                  {
                      $title = $_POST['item_name'][$key];
                      $courseID = $_POST['item_id'][$key];
                      $qty = $_POST['item_qty'][$key];
                      $fee = $_POST['item_fee'][$key];
                      $subtotal = $_POST['item_subtotal'][$key];
                      $totalFee += $subtotal;
                      $date=date("d-m-Y");
                      $array = array("title"=>$title, "course_id"=>$courseID, "qty"=>$qty, "fee"=>$fee, "subtotal"=>$subtotal, "user_id"=>$_SESSION["user_id"], "date"=>$date, "order_number"=>$orderNumber);
                      $results = insert($array,"booking");
                  }
    • Hello,

      I’m a bit confused with your code since I’m just a newbie.. Can you post your code along with the sample insert query to save the information in a table.

      Thanks so much!

    • yeah, can u provides the full example of the process.php. tq

  • Hi… I follow every step but I have a few problem…
    1. at my product there is no quantity product to choose.
    2. when add and remove cart the page did not back to current page.
    3. the product did not calculate the total.
    How to solve it…. I’m appreciate if anybody can help me….

     Reply
    • Hana, if you implemented the codes from the demo, you should be able to have your cart working fine. I think where you’ll have to do a little more work is at #1.

      You’ll have to add a textbox and edit your codes to work with it so that your products quantity will work concurrently with it. It might be a little tasking though. You just need parse the output from the textbox into your session values. That solves it either for adding or deducting quantities from your cart. Take some little time to work it out.

      @Saran Don’t you think including the textbox for quantity is necessary as many who aren’t good at PHP and maybe session handling are having issues with it? Though it’s not so much a task if they take some time to work it out.

    • TQ Marcel… I had solve number 1 and 2.. now I have problem that the total does not function.. the total didn’t calculate… the value is still $0.. my view_cart also doesn’t show list of cart… Please help me…

    • Hana, ensure you factored in the products total into the array that is used in outputting your products. To make it easier, var_dump() or print_r() your session array containing your cart details. See if you are actually collecting the products prices in the first place. If you are not then factor that in. If you are, from the output of what you have printed out from either var_dump() or print_r(), you should be able to fix your code to do your calculation well.

      Try var_dump($_SESSION[“products”]) or print_r($_SESSION[“products”]) depending on if you’re using the codes as on the source code here.

    • I’m not very understand… I have follow every step but my cart still doesn’t show info from shopping cart box…

  • HELLO.. I can not find mysql file in downloadable zip for database

     Reply
  • Can you tell me why you use base64_encode for return URL? Any particular reason?
    Thanks!

     Reply
    • No particular reason, you can use urlencode() or nothing at all.

    • This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

    • Ahhh ok. Thanks! Will there be update with “ajaxed” version? Im building my own, but I would like to learn from more experienced developers :)

  • hallo, it works very nice… how can i add a price selection instead of one price?

    echo ”;
    echo ‘price_A.’”>Produkt A ‘.$currency.$obj->price_A.”;
    echo ‘price_B.’”>Produkt B ‘.$currency.$obj->price_B.”;
    echo ‘price_C.’”>Produkt C ‘.$currency.$obj->price_C.”;
    echo ”;

    instead of

    echo ‘Price ‘.$currency.$obj->price.’ Add To Cart’; ?

     Reply
    • You can do it by using radio buttons with same name for all three with different values of each. Obviously Customer will chose only one so radio button is the solution.

    • You may want to consider using select (drop down) boxes, tends to be the norm for multiple prices. Though of course the tendency for that to be less SEO friendly but since this is with regards to a cart it’s not a big problem.

      I’ve worked in ecommerce professionally for the past 6-7 years.

  • Thanks for tutorial. Can you show us how to add AJAX (no page reload when adding items to cart)?
    Thanks!!

     Reply
  • I’m trying to get the checkout to work properly but running into a problem I can’t seem to resolve at all, despite checking around for 2 days now and reading hundreds of articles, I just can’t seem to get it to work no matter what I do. I’m thinking it’s an issue with the DoExpressCheckout function of the code as it doesn’t seem to be sending the product name or product code to Paypal.

    Basically the process works perfectly and goes to Paypal’s confirmation box showing everything correct there, I complete the payment but the emails to both the seller & buyer do not contain the product name or code, it’s just empty, all it shows is the price. It’s making me think that when the payment is finalised there’s something missing at that stage meaning all that’s sent is the price and quantity. The $paypal_data isn’t being sent on that final stage. Maybe I’m way off here but something’s definitely missing and not sending.

    It seems there’s been others having a similar problem so it would be great if you could help us out with any advice as right now it’s useless if no product details are sent, all I’m receiving is an email with an amount and therefore it’s impossible to process without item info.

    Cheers in advance for all your help.

     Reply
    • After your comment, I did a thorough assessment of Paypal express code here (http://bit.ly/1gbzf1P), and yes you are right, it is DoExpressCheckout, which needed exact parameters of SetExpressCheckOut, I have updated the code, now product info is available in transaction details.

    • Shaun Paul Johnston

      I managed to get it working how I needed but it did keep me up for 3 days trying to figure it out lol. Awesome that you’ve fixed the code, it’s no doubt better than my own as I’m a novice, so I’ll take a look and see if I can change mine to be cleaner and match you own.

      Cheers for checking it and have a great day :D

    • Hi Shaun. Did you manage to save the transaction id, item name, item number, and item quantity into the database successfully? Buyer Name, Email and ItemTotalPrice manage to appear in my database. I got undefined variables on the following values such as transaction id, item name, item number, and item qty. Please help. Thanks.

      $insert_row = $mysqli->query(“INSERT INTO BuyerTable
      (BuyerName,BuyerEmail,TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
      VALUES (‘$buyerName’,’$buyerEmail’,’$transactionID’,’$ItemName’,$ItemNumber, $ItemTotalPrice,$ItemQTY)”);

  • What if I have to add a product in cart with quantity=100 ?
    I have to click 100 times add to cart button and when I want to remove item from cart completely, I will have to press x 100 times, that will be a bad practice when we consider a shopping cart, please tell me how to overcome this issue?

     Reply
    • Good point, but in those circumstances, you can easily create a mechanism which will update session quantity, select-box is a good start or a quantity field.

    • Sir, even I am not an experienced developer but somehow I found solution to customize it for my self, but what a newbie will do? No offence but its the main point when we consider a cart system.

    • If it is allowed, I can share my solution for this circumstance.

    • It will be great if you can share your solution to this.
      Thanks in advance :)

    • yeah, why dont u just share with us? :)

  • First of all. Thank you for an AMAZING tutorial. So flawless and well put together. Really helped me grasp the concept of how a cart works.

    However, I cannot get my paypal sandbox to work so I’ve decided just to go with a cash on delivery solution. Meaning I’d like to create a mail script that sends me the cart information.
    I’ve tried

    1
    2
    3
     $cart_items = $_POST['item_name'];
    $cart_items =   $_POST['item_price'];
    $total  =       $_POST['total'];

    But this just outputs “Array”
    Would appreciate any help very much!

    Cheers!

     Reply
  • Hai.. tq for the code. it help me so much but I want to ask about the code.

    echo ”.$obj->product_name.”;
    echo ”.$obj->product_desc.”;
    echo ‘Price ‘.$currency.$obj->price.’ Add To Cart’;

    i don’t understand. can you explain how to make it works. thanks..:)

     Reply
    • Those were gotten from the select query statement
      $results = $mysqli->query(“SELECT product_name,product_desc, price FROM products WHERE product_code=’$product_code’ LIMIT 1”);
      $obj = $results->fetch_object();
      Selecting as objects and not fetch_num(),fetch_both(), etc is a faster architecture. If you don’t understand it then you can do your normal select query style better understood by you. Same results in the end if well implemented.

    • TQ Marcel.. now I finally understand..:)

  • Thanks a lot for this tutorial. I got the best of clue on how to design a shopping cart from here then went on to develop a more complex cart in the end. Thanks for sharing this tutorial.

     Reply
  • My shopping cart its completing the transactions sucessfully now but I still have a few questions,
    question 1: when adding products from my windows pc the quantity is added 1 item per each click but when I use an iPhone it adds 2 items on each tap and it does the same for removing items, not sure how that can happen???
    Question 2: I have the database table setup and ready to receive the transactions info but so far no info has been inserted for any of my live test transactions and on the return page (process.php) “confidential info removed” I am receiving this error:
    Success
    Your Transaction ID :
    Payment Received! Your product will be sent to you very soon!

    Stuff to store in database :

    Array
    (
    [RECEIVEREMAIL] =>
    [RECEIVERID] =>
    [EMAIL] =>
    [PAYERID] =>
    [PAYERSTATUS] => unverified
    [COUNTRYCODE] => US
    [SHIPTONAME] =>
    [SHIPTOSTREET] =>
    [SHIPTOCITY] =>
    [SHIPTOSTATE] =>
    [SHIPTOCOUNTRYCODE] => US
    [SHIPTOCOUNTRYNAME] => United%20States
    [SHIPTOZIP] =>
    [ADDRESSOWNER] => PayPal
    [ADDRESSSTATUS] => Confirmed
    [SALESTAX] => 0%2e00
    [SHIPAMOUNT] => 0%2e00
    [SHIPHANDLEAMOUNT] => 0%2e00
    [TIMESTAMP] => 2014%2d01%2d29T13%3a06%3a30Z
    [CORRELATIONID] =>
    [ACK] => Success
    [VERSION] =>
    [BUILD] => [FIRSTNAME] =>
    [LASTNAME] =>
    [TRANSACTIONID] =>
    [TRANSACTIONTYPE] => expresscheckout
    [PAYMENTTYPE] => instant
    [ORDERTIME] => 2014%2d01%2d29T13%3a05%3a34Z
    [AMT] => 0%2e01
    [FEEAMT] => 0%2e01
    [TAXAMT] => 0%2e00
    [CURRENCYCODE] => USD
    [PAYMENTSTATUS] => Completed
    [PENDINGREASON] => None
    [REASONCODE] => None
    [PROTECTIONELIGIBILITY] => Eligible
    [PROTECTIONELIGIBILITYTYPE] => ItemNotReceivedEligible%2cUnauthorizedPaymentEligible
    [L_QTY0] => 1
    [L_TAXAMT0] => 0%2e00
    [L_CURRENCYCODE0] => USD
    )

     Reply
    • Hi bro. I have the same problem as you. This is actually the last step. My table did not show any record after the transaction is successful. Have you solve the problem yet? Thanks. :)

  • Sir my paypal page is error genrate
    Error : Security header is not valid
    Array
    (
    [TIMESTAMP] => 2014%2d01%2d27T18%3a28%3a00Z
    [CORRELATIONID] => 6474e6d1b9e37
    [ACK] => Failure
    [VERSION] => 76%2e0
    [BUILD] => 9285531
    [L_ERRORCODE0] => 10002
    [L_SHORTMESSAGE0] => Security%20error
    [L_LONGMESSAGE0] => Security%20header%20is%20not%20valid
    [L_SEVERITYCODE0] => Error
    )
    Pleas solve my problem sir

     Reply
  • I got the shopping cart partially working, but I am still getting errors
    When I click on pay now on view_cart.php it takes me to process.php but with error:
    Warning: Cannot modify header information – headers already sent by (output started at /hermes/bosoraweb177/b2883/ipg.weallworkcom/paypal-shopping-cart/paypal-express-checkout/config.php:2) in /hermes/bosoraweb177/b2883/ipg.weallworkcom/paypal-shopping-cart/paypal-express-checkout/process.php on line 67

    I also get these errors mentioned by 2 other people here:
    when the user try to remove from cart error occurs:
    Warning: Invalid argument supplied for foreach() in /hermes/bosweb/web274/b2158/ipg.nycegyptcom/store/cart_update.php on line 62 Warning: Cannot modify header information – headers already sent by (output started at /hermes/bosweb/web274/b2158/ipg.nycegyptcom/store/cart_update.php:62) in /hermes/bosweb/web274/b2158/ipg.nycegyptcom/store/cart_update.php on line 84

    I am not sure on what page and line to enter the TOKEN number and the returnUrl and not sure if to use the index.php page as the return url or to have a different page as return url.
    Please help

     Reply
  • my products are not adding in the cart when i click add to cart button

     Reply
  • Hy sir pleas help me
    error this code
    Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user ‘root’@’localhost’ (using password: NO) in /home/comfort/public_html/config.php on line 8
    Fatal error: Call to a member function query() on a non-object in /home/comfort/public_html/index.php on line 432
    sir pleas reply fast
    Thanks sir

     Reply
  • When user removes all the items from cart – I get following 2 errors – please advise :
    Warning: Invalid argument supplied for foreach() in s/cart_update.php on line 62

    Warning: Cannot modify header information – headers already sent by (output started at /home/esuratne/public_html/demo/lmt/s/cart_update.php:62) in s/cart_update.php on line 84

     Reply
    • Hi OxEgen, I had the same problem and I just discovered the solution.

      Simply put
      $_SESSION[“products”] = $product;
      on line 80 outside of the foreach loop and it should work.

    • Hello Philippe I am also dealing with the same issue, and I just viewed your comment left for OxEgen
      would you mind showing me how I can get $_SESSION[“products”] = $product; out of the foreach loop?
      I have no idea on how to do that, Thanks

    • You just have to put $_SESSION[“products”] = $product; after the foreach loop, like so:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      foreach ($_SESSION["products"] as $cart_itm) //loop through session array var
      {
          if($cart_itm["code"]==$product_code) //item exist in the list
          {
              //continue only if quantity is more than 1
              //removing item that has 0 qty
              if($cart_itm["qty"]>1)
              {
                  $qty = $cart_itm["qty"]-1; //just decrese the quantity
                  //prepare array for the products session
                  $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$qty, 'price'=>$cart_itm["price"]);
              }
          }
          else
          {
              $product[] = array('name'=>$cart_itm["name"], 'code'=>$cart_itm["code"], 'qty'=>$cart_itm["qty"], 'price'=>$cart_itm["price"]);
          }
      }
      //set session with new array values
      $_SESSION["products"] = $product;
    • Wow that worked,
      Thank you very much for your help Philippe

    • Hi Philippe Tellier / Luis,

      I already had $_SESSION[“products”] = $product; on line 80 – but it didn’t work and had dropped the idea of using. But now I guess I’ll have to try again. Will get back in a day or 2.

      Thanks,
      oxEgen

    • OxEgen

      Cut the $_SESSION[“products”] = $product; from line 80 and paste it after the next curly bracket “}” (the end of the foreach loop).

  • hi
    this is my website coming soon….

     Reply
  • Somehow the empty card routine removes all entries, not just the one with the correct product ID. What can go wrong?

     Reply
  • Hi, can you please help me.
    Can you please tell me how to link the view Item summary to a web form that my customers can fill in (name, address) then send me a confirmation with Items he selected to order. ( I wont be using the payment process)

    Thank you in advance !

     Reply
  • I solved it aaaaaaaaaaaaa ouffff, isse comes from my side. forgot to import the mysql_import file.

    its working hihih im proud of myself :D

     Reply
  • Hello, can you plz help me ! :(
    I am trying hard to get your code to work, but i always get this :

    Your Shopping Cart
    Your Cart is empty

    nothing else, plzz help. i dont know where the issue comes from. Thanks alot

     Reply
  • I fixed my question already! Another question though.
    How can I send ordered/cart items to my mail?
    For school purposes.

     Reply
  • Hello, i just want to ask how to add a next page with different products without the cart clearing? Please answer

     Reply
  • thank you for reply. how to install it. I m not export in networking. Please help me

     Reply
  • when i click pay now button goes to process.php. But i saw this error
    Fatal error: Call to undefined function curl_init() in C:\wamp\www\paypal-shopping-cart-example-688751\paypal-express-checkout\paypal.class.php on line 23.
    Please solution me

     Reply
  • Hi, I want to ask if I would like to link the customer order’s item into database. How should I do it?

     Reply
  • Hi Saran

    Thank you very much for replying, especially so quickly :)!

    I’ve got it running but I keep encountering this error message.

    Warning: mysqli::mysqli(): (42000/1044): Access denied for user ‘______’@’%’ to database ‘products’ in /usr/local/www/project/____/config.php on line 8

    This is followed by

    Warning: mysqli::query(): Couldn’t fetch mysqli in /usr/local/www/project/_____/index.php on line 21

     Reply
    • Dave, ensure you have created a Database in your Localhost with the same name you’re using in your application’s database name configuration. Ensure the passwords too correspond then you should be able gain access to do your queries.

  • I apologise if this is a very basic question but i’m totally new to html.

    I downloaded the code, and made the database. But how do i execute the code I want to see it and Chrome and test it, but when i open with chrome i just see a copy of the php code

     Reply
  • hi thanks very much for the source code
    please i have a problem on how to echo pictures from the database
    i have added one row in the table this is the code
    $results = $mysqli->query(“SELECT * FROM products WHERE product_img_name=’images/RC mdpv.jpg’ ORDER BY id ASC”);
    if ($results) {
    //output results from database
    while($obj = $results->fetch_object())
    {

    echo ”;
    echo ”;
    echo ‘product_img_name.'”>’;
    echo ”.$obj->product_desc.”;
    echo ”.$obj->product_name.”;
    echo ”.$obj->product_desc2.”;
    echo ‘Price ‘.$currency.$obj->price.’ Add To Cart’;
    echo ”;
    echo ‘product_code.'” />’;
    echo ”;
    echo ”;
    echo ”;
    echo ”;
    }

    }
    ?>

    please help
    waiting……..

     Reply
    • more info. You can do this:

      Select * From Products Where product_img_name = “RC mdpv.jpg” Order by id ASC

  • hallo, it works very nice… how can i add a price selection instead of one price?

    echo ”;
    echo ‘price_A.'”>Produkt A ‘.$currency.$obj->price_A.”;
    echo ‘price_B.'”>Produkt B ‘.$currency.$obj->price_B.”;
    echo ‘price_C.'”>Produkt C ‘.$currency.$obj->price_C.”;
    echo ”;

    instead of

    echo ‘Price ‘.$currency.$obj->price.’ Add To Cart’; ?

     Reply
  • I want to know how to do pagenation through shopping cart.

     Reply
  • Hi everything works fine for me but i cannot display the pictures store in the database.can you help me please ?

     Reply
  • in process.php there are errors:
    foreach($_POST[‘item_name’] as $key=>$itmname)
    also:

    1
    $paypal_data .= '&L_PAYMENTREQUEST_0_QTY'.$key.'='. urlencode($_POST['item_qty'][$key]);

    and the 3 lines after it. and:

    1
    $padata = '&CURRENCYCODE='.urlencode($PayPalCurrencyCode).

    and all the lines after it.

     Reply
  • when the user try to remove from cart error occurs:
    Warning: Invalid argument supplied for foreach() in /hermes/bosweb/web274/b2158/ipg.nycegyptcom/store/cart_update.php on line 62 Warning: Cannot modify header information – headers already sent by (output started at /hermes/bosweb/web274/b2158/ipg.nycegyptcom/store/cart_update.php:62) in /hermes/bosweb/web274/b2158/ipg.nycegyptcom/store/cart_update.php on line 84

     Reply
  • Great tutorial! Thanks much… You saved me a lot of headaches!!!

    Regards,
    Gabriella

     Reply
  • hi, your code is really helping my school project, but i have one problem, i want to pass all the cart_item data into a temporary table in my database, i dont have any idea, how to take the value from the session and insert them to the database

     Reply
  • Hi
    Thank you for this script it is great, I’m doing an e-commerce at school, and find this is very helpful, however I get this error, when I try to add a product to the cart,

    Fatal error: Call to a member function fetch_object() on a non-object in C:\Users\6261_21314\PP3\Bettys_Outdoor_Clothing\cart_update.php on line 13

    here is the code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    //add item in shopping cart
    if(isset($_POST["type"]) &amp;&amp; $_POST["type"]=='add')
    {
        $product_code   = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
        $return_url     = base64_decode($_POST["return_url"]); //return url
       
        //MySqli query - get details of item from db using product code
        $results = $mysqli-&gt;query("SELECT product_name,price FROM products WHERE product_code='$product_code' LIMIT 1");
        $obj = $results-&gt;fetch_object(); //THIS IS THE PROBLEM LINE HERE

    hope to hear from you soon, thanks.

     Reply
  • Hello.
    It is a very nice script you have done here and I thank you for that.
    However, I’ve got stuck into a problem.
    I am creating a small website using your shopping script.
    Here it is what I am doing right now: http://moviesbay.net/website
    When the user goes to the product page and is clicking on yhe add to cart icon for the first time, everything is going fine.
    But if the user clicks on the shop link (to return to the shop) and then is choosing another product from the list and is clicking on the add to cart button, the code where the Total resides is being executed twice.

    Can you give me a hand with that?
    Regards,
    Ciprian.

     Reply
    • My bad and I’m sorry for that. I was not paying attention to foreach function. Everything works just fine. Thank you again for this beatuful and simple to use e-commerce script.

  • this is very helpful..
    but i want to ask if i want to select products from different categories then how should i do that?

    please help

     Reply
    • You have to create another row in your database called categories.

      Then, create other pages for each category and in your sql statement, where the code is

      1
      $results = $mysqli->query("SELECT * FROM products ORDER BY id ASC");

      you have to add the bolded part like this

      1
      $mysqli->query("SELECT * FROM products WHERE category = 'your category' ORDER BY id ASC");

      Regards,
      Ciprian.

    • Hi, can you please help me.
      Can you please tell me how to link the view Item summary to a web form that my customers can fill in (name, address) then send me a confirmation with Items he selected to order. ( I wont be using the payment process)

      Thank you in advance !

  • Hi, it works perfect on 127.0.0.1, when I try to host in on the server, it doesn’t redirect. When I click to Add Product in Cart, displays blank page. :(

     Reply
  • Hi, I’m just starting off in the web development industry and I just wanted to say thanks for you awesome tutorials. Thanks

     Reply
  • Adding different products in different pages, how can it be linked and updated with the cart?

     Reply
  • Thanks!!
    Question: change product quantity??

     Reply
    • Hello, you can change the price directly in your database.

    • I think , we add a $number_p in file index.php, then create function quantityProduct() to retuen quantity products, will auto update in database. However , can change layout a few.