MySQL
  Home arrow MySQL arrow Page 3 - 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 - Displaying the items


    (Page 3 of 6 )

    As I'm sure you can guess, displaying the list of items from our items table is fairly easy. Because we will be displaying items on one page, and showing a shopping cart on another page, we will create a file that will store the connection details of the database and two functions to connect to and work with the database. Create a file called db.php and enter the following code into it:

    <?php

    // This page contains the connection routine for the
    // database as well as getting the ID of the cart, etc

    $dbServer = "localhost";
    $dbUser = "admin";
    $dbPass = "password";
    $dbName = "cart";

    function ConnectToDb($server, $user, $pass, $database)
    {
    // Connect to the database and return
    // true/false depending on whether or
    // not a connection could be made.

    $s = @mysql_connect($server, $user, $pass);
    $d = @mysql_select_db($database, $s);

    if(!$s || !$d)
    return false;
    else
    return true;
    }

    function GetCartId()
    {
    // This function will generate an encrypted string and
    // will set it as a cookie using set_cookie. This will
    // also be used as the cookieId field in the cart table

    if(isset($_COOKIE["cartId"]))
    {
    return $_COOKIE["cartId"];
    }
    else
    {
    // There is no cookie set. We will set the cookie
    // and return the value of the users session ID

    session_start();
    setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
    return session_id();
    }
    }

    ?>


    First off, we define four variables to hold the details of our MySQL database's server, username, password, and database name respectively. Next, we have the ConnectToDb function, which uses our database variables and connects to our MySQL database:

    $s = @mysql_connect($server, $user, $pass);
    $d = @mysql_select_db($database, $s);

    if(!$s || !$d)
    return false;
    else
    return true;


    Notice how the calls to mysql_connect and mysql_select_db are prepended with the @ symbol. This tells PHP not to spit any errors if the connect fails. If either of the connection or database selection functions fail, then ConnectToDb returns false. Otherwise it returns true, indicating a successful connection.

    The GetCartId function makes use of one cookie variable to track a user across multiple sessions. It starts by checking if the cartId cookie variable is set. If not, it grabs the users session ID and sets it as a cookie value which expires in 30 days (the expiry date of the setcookie function is specified in seconds, so (3600 * 24) * 30 means 3600 seconds ( 1 hour) * 24 (1 day) * 30 (1 month)). The GetCartId function is used in combination with the MySQL cart table to track which user has added which items to their cart.

    Db.php is included by both our item listing page and cart. The item listing page is called products.php, and starts off like this:

    <?php

    // This page will list all of the items
    // from the items table. Each item will have
    // a link to add it to the cart

    include("db.php");

    // Get a connection to the database
    $cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
    $result = mysql_query("select * from items order by itemName asc");
    ?>


    As you can see, we include db.php and call the ConnectToDb function to attain a connection to our MySQL database. Next, we grab the entire list of items from the items table, and store the result in the $result variable.

    Each item will be displayed as part of a table. We output some HTML tags and then the beginning row of our table before starting a loop through each item, like this:

    <?php
    while($row = mysql_fetch_array($result))
    {
    ?>


    For each item, we output its name, price, description, and a link to add it to that users shopping cart:

    <tr>
    <td width="30%" height="25">
    <font face="verdana" size="1" color="black">
    <?php echo $row["itemName"]; ?>
    </font>
    </td>
    <td width="10%" height="25">
    <font face="verdana" size="1" color="black">
    $<?php echo $row["itemPrice"]; ?>
    </font>
    </td>
    <td width="50%" height="25">
    <font face="verdana" size="1" color="black">
    <?php echo $row["itemDesc"]; ?>
    </font>
    </td>
    <td width="10%" height="25">
    <font face="verdana" size="1" color="black">
    <a href="cart.php?action=add_item&id=<?php echo $row["itemId"]; ?>&qty=1">Add Item</a>
    </font>
    </td>
    </tr>
    <tr>
    <td width="100%" colspan="4">
    <hr size="1" color="red" NOSHADE>
    </td>
    </tr>


    Lastly, we close all table and HTML tags, and display a link to the shopping cart, called cart.php (we will create this in the next step):

    <tr>
    <td width="100%" colspan="4">
    <font face="verdana" size="1" color="black">
    <a href="cart.php">Your Shopping Cart &gt;&gt;</a>
    </font>
    </td>
    </tr>
    </table>
    </body>
    </html>


    Loading up products.php in my browser, I received the following page:

    The products.php page

    The "Add Item" link for each item links to cart.php. Let's now take a look at the cart.php page, which lets us add, update and delete items from our shopping cart.

    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 6 hosted by Hostway
    Stay green...Green IT