www.webdeveloper.com
Results 1 to 11 of 11

Thread: PHP Shopping Cart

  1. #1
    Join Date
    Mar 2009
    Posts
    9

    PHP Shopping Cart

    Ok, so I'm developing a shopping cart. I've kind of hit a brick wall with it though.

    PHP Code:
    <?php session_start(); ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style type="text/css">
    <!--
    .cellunderline {
        border-bottom-width: thin;
        border-bottom-color: #000;
        border-bottom-style: solid;
        border-top-width: 0px;
        border-right-width: 0px;
        border-left-width: 0px;
        border-top-style: none;
        border-right-style: none;
        border-left-style: none;
    }
    .celloverline {
        border-top-width: thin;
        border-right-width: 0px;
        border-bottom-width: 0px;
        border-left-width: 0px;
        border-top-style: solid;
        border-right-style: none;
        border-bottom-style: none;
        border-left-style: none;
        border-top-color: #000;
    }
    -->
    </style></head>

    <body>

    <table width="100%" border="0">
      <tr>
        <td class="cellunderline">Name</td>
        <td class="cellunderline">Description</td>
        <td class="cellunderline">Category</td>
        <td class="cellunderline">Price</td>
      </tr>
      <tr>
        <td>Frames</td>
        <td align="center">--</td>
        <td align="center">--</td>
        <td align="center">--</td>
      </tr>
    <?php
    if (isset($_POST['serial'])) {
        
    $_SESSION['cart'] = $_SESSION['cart'] . "
    <tr>
    <td>" 
    $_POST['serial'] . "</td>
    <td>" 
    $_POST['description'] . "</td>
    <td>" 
    $_POST['category'] . "</td>
    <td align='right'>" 
    $_POST['price'] . "</td>
    <tr>
        "
    ;
            echo 
    $_SESSION['cart'];
    }

    ?>
      <tr>
        <td class="celloverline">Subtotal</td>
        <td align="center" class="celloverline">--</td>
        <td align="center" class="celloverline">--</td>
        <td align="right" class="celloverline">
        <?php 
                
    if (isset($_SESSION['subtotal'])) {
                
    $_SESSION['subtotal'] = $_SESSION['subtotal'] + $_POST['price'] ;}
            else {
                
    $_SESSION['subtotal'] = "0.00" ;}
        
    printf("%10.2f\n"$_SESSION['subtotal'] );
        
    ?>
        </td>
      </tr>
      <tr>
      <td height="25"></td>
      <td></td>
      <td align="center">

    </td>
      <td></td>
      </tr>
    </table>
    <p></p>
    </body>
    </html>
    My questions are:
    1. How would I code a "reset cart" button, to completely destroy the session and start a new one? (Customers do not have accounts on this site)

    2. Have I implemented this code incorrectly? Could it be done better? (All variables are sent from the "Add to Cart" buttons on the catalog page)

    3. Could I avoid this hassle entirely by using some 3rd party application? (Budget is a major issue)

    Using Dreamweaver CS4 on Vista. Any comments or help is much appreciated!

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,338
    It looks like you are using the session to store HTML output.

    I would instead only store an array of product IDs and quantities, e.g.:
    PHP Code:
    $_SESSION['cart'][1234] = 2// product ID '1234' with a quantity of '2'
    $_SESSION['cart'][2345] = 3// product ID 2345' with a quantity of '3' 
    Then for each usage of cart data in your processing and/or page display, you would use the session cart data as the basis for a DB query, e.g. (untested, for ideas only):
    PHP Code:
    if(!empty($_SESSION['cart']))
    {
       
    $serials array_keys($_SESSION['cart']);
       
    $sql "SELECT * FROM products WHERE serial IN (" implode(','$serials) . ")";
       
    $result mysql_query($sql);
       
    $subtotal 0;
       while(
    $row mysql_fetch_assoc($result))
       {
          
    $qty $_SESSION['cart'][$row['serial']];
          
    printf("
             <tr><td>%d</td><td>%s</td><td>%d</td><td>$%.2f</td><td>$%.2f</td></tr>"
    ,
             
    htmlentities($row['serial']),
             
    htmlentities($row['description']),
             
    $qty,
             
    $row['price'],
             
    $row['price'] * $qty
          
    );
       }

    This is assuming "serial" is an integer. If a string, some additional processing would be needed for SQL escaping and quoting in the IN() expression.

    As far as clearing the cart, all you would need is to do an unset($_SESSION['cart']); to remove all items.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Mar 2009
    Posts
    9
    Thanks for the quick reply!

    The serials will be strings, unfortunately. It's the only way my client could track his inventory (taking an established business online)

    I've already got the SQL database for the catalog done. There are 5 tables, each for a seperate category of items. Would this possibly make it any simpler?

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,338
    Quote Originally Posted by c_anthony07 View Post
    Thanks for the quick reply!

    The serials will be strings, unfortunately. It's the only way my client could track his inventory (taking an established business online)
    That is no problem other than a bit more complexity in setting up the queries, as string values need to be filtered and quoted. This could be avoided though if your database structure used integer primary key field in addition to the serial number field. Then you would use that value (the primary key integer) instead of the serial number in the cart session data.

    I've already got the SQL database for the catalog done. There are 5 tables, each for a seperate category of items. Would this possibly make it any simpler?
    This would make things somewhat hairier, as you would have to somehow also track the category in the session data, and probably run separate queries. A more "normalized" approach would be to have a single product table that stores the data elements common to all products, then possibly have additional tables and possibly relation tables for tracking info specific to different categories and related to the main product table by the product primary key.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #5
    Join Date
    Mar 2009
    Posts
    9
    I'm using a normal integer key as well as serials. ProductID and Serial are two entries on the table.

    As for the database... ugh. Redoing that will require redoing the catalog page as well. Blah.

    I've got all the major messengers if you'd like. Probably converse faster. PM me if your interested.

  6. #6
    Join Date
    Mar 2009
    Posts
    9
    Ok, so here's a thought...

    If I streamlined my database structure, listing all products within one table (using other tables for category references), I'd need to:

    - be able to list products by category in the catalog page
    - use the Add to Cart button to send the ProductID to the cart form, which would then add a row of information based on the information present in the table.

    Or, would it be better to have a seperate script process the "Add to Cart" and then send them to the cart page with the updated information?

  7. #7
    Join Date
    Mar 2009
    Posts
    9
    I've redone my catalog and my database. I now have two tables: "products" which lists all products, with an integer for category_id; and "categories" which assigns integers to all categories. So now all my products have a unique product_id (as an integer)

  8. #8
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,338
    Quote Originally Posted by c_anthony07 View Post
    I've redone my catalog and my database. I now have two tables: "products" which lists all products, with an integer for category_id; and "categories" which assigns integers to all categories. So now all my products have a unique product_id (as an integer)
    I think you'll find this sort of normalization will help keep things more manageable. You should now be able to just store the product ID and quantity of each cart item in your session "cart", then use those IDs as needed to query the database for whatever additional info you need to display the cart contents, calculate price sub-totals and totals, etc. in any given script.

    If you still need help with specific queries, we may need the details on the current DB structure in order to help.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  9. #9
    Join Date
    Mar 2009
    Posts
    9
    So, I've got my "Add to Cart" button sending the values "product_id" and "price" to my cart page.

    Can I store multiple product id's in the $_SESSION['cart'] array? I think I'm missing something about arrays...

    for example, can the $_SESSION['cart'] = 36 & 45 to show two different items in the cart?

  10. #10
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,338
    I would probably use an additional array dimension:
    PHP Code:
    $_SESSION['cart'][$id] = $quantity
    Then to loop through the cart you could use a foreach():
    PHP Code:
    foreach($_SESSION['cart'] as $id => $quantity)
    {
       echo 
    "<p>Product ID: $id, Quantity: $quantity</p>\n";

    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  11. #11
    Join Date
    Mar 2009
    Posts
    9
    So how would you go about storing the values? because I'd like for it to be something like...

    PHP Code:
    $_SESSION['cart'][insert product ID integer here
    and then be able to call data from the database for each product.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles