MySQL
  Home arrow MySQL arrow Page 5 - 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 
Sun Developer Network 
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 / 124
    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 ShowCart function


    (Page 5 of 6 )

    At this point we need a way to list all of the items in our shopping cart, as well as a total cost for all of those items. ShowCart handles all of this. It also provides a drop down list for each item, so that its quantity can be easily updated.

    ShowCart starts off by using an SQL INNER JOIN query to get a list of items from the cart table, and also each items details from the items table:

    $result = mysql_query("select * from cart inner join items on cart.itemId = items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName asc");

    Once the list of items is retrieved, each item is displayed as part of a table, as a table row:

    while($row = mysql_fetch_array($result))
    {
    // Increment the total cost of all items
    $totalCost += ($row["qty"] * $row["itemPrice"]);
    ?>
    <tr>
    <td width="15%" height="25">
    <font face="verdana" size="1" color="black">
    <select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">
    <?php

    for($i = 1; $i <= 20; $i++)
    {
    echo "<option ";
    if($row["qty"] == $i)
    {
    echo " SELECTED ";
    }
    echo ">" . $i . "</option>";
    }
    ?>
    </select>
    </font>
    </td>
    <td width="55%" height="25">
    <font face="verdana" size="1" color="black">
    <?php echo $row["itemName"]; ?>
    </font>
    </td>
    <td width="20%" height="25">
    <font face="verdana" size="1" color="black">
    $<?php echo number_format($row["itemPrice"], 2, ".", ","); ?>
    </font>
    </td>
    <td width="10%" height="25">
    <font face="verdana" size="1" color="black">
    <a href="cart.php?action=remove_item&id=<?php echo $row["itemId"]; ?>">Remove</a>
    </font>
    </td>
    </tr>
    <?php
    }


    The running tally of each item in the users shopping cart is kept as the $totalCost variable:

    // Increment the total cost of all items
    $totalCost += ($row["qty"] * $row["itemPrice"]);


    The quantity of each item is multiplied by its price, and is then added to the $totalCost variable using the += operator, which is the same as:

    $totalCost = $totalCost + ($row["qty"] * $row["itemPrice"]);

    As I mentioned above, the quantity for each item is displayed in a drop down list. This list is generated with the following code:

    <select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">
    <?php
    for($i = 1; $i <= 20; $i++)
    {
    echo "<option ";
    if($row["qty"] == $i)
    {
    echo " SELECTED ";
    }
    echo ">" . $i . "</option>";
    }
    ?>
    </select>


    The <select> tag contains a trigger for the onChange event, which calls a JavaScript function called UpdateQty. UpdateQty is defined at the top of the ShowCart function, and looks like this:

    <script language="JavaScript">

    function UpdateQty(item)
    {
    itemId = item.name;
    newQty = item.options[item.selectedIndex].text;

    document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;
    }

    </script>


    Once called, UpdateQty takes the quantity of the selected item as well as the items ID (which is the name of the drop down list) and passes them as query string variables to cart.php. For example, if I updated the quantity of a product whose ID was 5 to 4, then I would be redirected to the following URL:

    cart.php?action=update_item&id=5&qty=4

    Lastly, ShowCart displays the total cost of all items in the users cart:

    <tr>
    <td width="100%" colspan="4">
    <hr size="1" color="red" NOSHADE>
    </td>
    </tr>
    <tr>
    <td width="70%" colspan="2">
    <font face="verdana" size="1" color="black">
    <a href="products.php">&lt;&lt; Keep Shopping</a>
    </font>
    </td>
    <td width="30%" colspan="2">
    <font face="verdana" size="2" color="black">
    <b>Total: $<?php echo number_format($totalCost, 2, ".", ","); ?></b>
    </font>
    </td>
    </tr>


    After adding all three games to the shopping cart, here’s how cart.php looked in my browser:

    Cart.php in action

    When I clicked on the qty field for SSX Tricky and changed it from 2 to 4, the page automatically updated its quantity and the total price, as shown below:

    Updating an items quantity field

    Just before I wrap up this article, I thought that I should mention the persistence of our shopping cart. If you close your browser after you’ve added some items to your cart and then reopen it, you'll see that those items are still in your cart. This results from the way that we’ve used a cookie to track a session ID that persists for up to one month, meaning that the contents of your cart will remain in-tact for the next month.

    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
     

    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-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT