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>£'.$row['price'].'</td>';
$total = $total + $row['price'];
echo '</tr>';
echo '</table>';
echo '<p>Total: £'.$total.'</p>';
mysql_close($con);
?>