Jump to content

Display Shopping Basket Items


Dysan

Recommended Posts

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


?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.