...

View Full Version : Display Shopping Basket Items



Cerby
11-17-2007, 02:53 AM
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.


<?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);


?>

Inigoesdr
11-17-2007, 06:08 AM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum