MySQL
  Home arrow MySQL arrow Page 4 - Building A Persistent Shopping Cart With P...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Building A Persistent Shopping Cart With PHP and MySQL
By: Mitchell Harper
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 149
    2002-05-18

    Table of Contents:
  • Building A Persistent Shopping Cart With PHP and MySQL
  • Creating the database
  • Displaying the items
  • The cart.php script
  • The ShowCart function
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building A Persistent Shopping Cart With PHP and MySQL - The cart.php script


    (Page 4 of 6 )

    A shopping cart must perform four functions. It must allow users to add and remove products from their cart. It must allow them to change the quantity of items for each product in their cart, and it must also allow them to actually see the products in their cart, as well as a cumulative total of all of the products in their cart.

    Cart.php contains four functions that implement the work described in the previous paragraph. Cart.php requires on a query string variable, action, to tell it what to do:

    <?php

    include("db.php");

    switch($_GET["action"])
    {
    case "add_item":
    {
    AddItem($_GET["id"], $_GET["qty"]);
    ShowCart();
    break;
    }
    case "update_item":
    {
    UpdateItem($_GET["id"], $_GET["qty"]);
    ShowCart();
    break;
    }
    case "remove_item":
    {
    RemoveItem($_GET["id"]);
    ShowCart();
    break;
    }
    default:
    {
    ShowCart();
    }
    }


    As you can see, I'm using the $_GET associative array, which was introduced with PHP version 4.1, and made standard with PHP version 4.2. In PHP 4.2, $HTTP_GET_VARS is deprecated, so you should get into the habit of using $_GET and $_POST instead of $HTTP_GET_VARS and $HTTP_POST_VARS. Using $_GET is quicker too, because it is automatically globally scoped, whereas $HTTP_GET_VARS is not.

    Looking at the switch statement above, we have four possible cases, each of which is discussed below:
    • add_item: When the user clicks on the "Add Item" for an item on the products.php page, this case will be called. It calls the AddItem function, passing in an items ID and quantity.
    • update_item: Updates the quantity of an item in the users shopping cart. As you will see shortly, each item in the cart is displayed with a drop down list, that, when changed, automatically updates the numeric of a specific item in the users shopping cart.
    • remove_item: Deletes an item from the cart table for the current user.
    If the cart.php page is called up with no query string parameters, then the ShowCart function is called. Let's start by looking at the AddItem function.

    AddItem accepts two parameters: The ID of the item to add to the cart, and the number of that item to add:

    function AddItem($itemId, $qty)

    The main part of the AddItem function checks whether or not this item already exists in the users cart. If it does, then its quantity field is updated and it isn't added again:

    $result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

    $row = mysql_fetch_row($result);
    $numRows = $row[0];

    if($numRows == 0)
    {
    // This item doesn't exist in the users cart,
    // we will add it with an insert query

    @mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() . "', $itemId, $qty)");
    }
    else
    {
    // This item already exists in the users cart,
    // we will update it instead

    UpdateItem($itemId, $qty);
    }


    Looking at the code above, we can see that if $numRows equals zero (i.e. the item isn’t already in the users cart) then the item is added to the cart table. If not, the items quantity field is updated by calling the UpdateItem function, which is described below.

    UpdateItem accepts two parameters, in the same way that the AddItem function does:

    function UpdateItem($itemId, $qty)

    It executes a simple UPDATE SQL query against the cart table, updating the quantity of one specific item. The cookieId field is used to match the users session ID to that particular product, making sure that the quantity is only updated for that item and the current user:

    mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");

    Removing an item is a simple matter of the RemoveItem function being called. It accepts just one parameter, which is the ID of the item to delete:

    function RemoveItem($itemId)

    Once connected to the database, a simple SQL DELETE query removes the item from the current users cart:

    mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

    All of these functions are good, but to actually call them, we need to look at the ShowCart function, which is what we will do on the next page.

    More MySQL Articles
    More By Mitchell Harper


       · Holy crap dude. You leave instructional pages unfinished, php scripts ending...
       · hi, nice article. helped me to get my cart faster built.but you should take more...
       · hi were can i download the full script of this shopping cart? it nice but there is...
       · +1 bump.... hard to follow for a newbie like me as well.
       · Its a good code, easy to follow too except that its a rather simple model.If you...
       · Dear I am currently working on shopping cart for shirt site i can send you when i...
       · If you have built the cart PLEASE EMAIL ME THE CODE. THANKS
       · this is so annoying its not even a complete shopping cart script
       · nice script! but is it possible to add like pictures in the db-code(and change...
       · As he said, you should know some PHP and Java.It became quite clear to me that I...
       · i need a complete script, can u pls mail me?
       · Where can i get this full shopping cart code?
       · Why does nobody give a straight forward scripts for noobs please upload a link for...
     

    MYSQL ARTICLES

    - MySQL and BLOBs
    - Two Lessons in ASP and MySQL
    - Lord Of The Strings Part 2
    - Lord Of The Strings Part 1
    - Importing Data into MySQL with Navicat
    - Building a Sustainable Web Site
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - PhpED 3.2 – More Features Than You Can Poke ...
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - Security and Sessions in PHP
    - Setup Your Personal Reminder System Using PHP
    - Create a IP-Country Database Using PERL and ...
    - Developing a Dynamic Document Search in PHP ...







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 10 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek