Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Banned
    Join Date
    Oct 2007
    Posts
    52
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Display Shopping Basket Items

    The following code creates a shopping cart, where a user can click on a "Add X to Basket" link, to include the item/product in a shopping list

    Each time a "Add X to Basket" link is clicked, the product ID, is appended to a session called "Cart".

    How do I display the products title, and price in the table, to reflect what ID are stored in the "Cart session variable.

    Code:
    <?php
    session_start();
    $con = mysql_connect("localhost","ODBC","");
    if (!$con)
    {
      die(mysql_error());
    }
    
    function writeShoppingCart()
    {
      $cart = $_SESSION['cart'];
      if (!$cart)
      {
        echo '<p>You\'re shopping basket is empty!</p>';
      }
      else
      {
        // Parse the cart session variable
        $items = explode(',',$cart);
        $s = (count($items) > 1) ? 's':'';
        echo '<p>Shopping Cart: <a href="cart.php">'.count($items).' item'.$s.'</a></p>';
      }
    }
    
    ///////////////////////////////////////////////////////////
    
    $cart = $_SESSION['cart'];
    if ($cart)
    {
      $cart .= ','.$_GET['id'];
    }
    else
    {
      $cart = $_GET['id'];
    }
    $_SESSION['cart'] = $cart;
    
    ///////////////////////////////////////////////////////////
    
    echo "Shopping Cart Product ID's: " . $_SESSION['cart'];
    
    ///////////////////////////////////////////////////////////
    
    echo writeShoppingCart();
    $total = 0;
    echo '<table border="1">';
    
    mysql_select_db("MP3", $con);
    
    $id = $_GET['id'];
    
    $result = mysql_query("SELECT * FROM books WHERE id='$id'");
    $row = mysql_fetch_assoc($result);
    
    echo '<tr>';
    echo '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>';
    echo '<td>'.$row['title'].' by '.$row['author'].'</td>';
    echo '<td>&pound;'.$row['price'].'</td>';
    $total = $total + $row['price'];
    
    echo '</tr>';
    echo '</table>';
    echo '<p>Total: &pound;'.$total.'</p>';
    
    mysql_close($con);
    
    
    ?>

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    explode() the ids into an array like the write function does, and then you have to select the data for each item from the database using the array of ids. Please don't ask "How do I do that?". Lookup the functions, do some research, and learn something for yourself.


  •  

    Posting Permissions

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