I have a database full of products.
I can view each individual product fine and it works great. Now i have added an "Add to Basket Link".
This is where i get lost using sessions etc.
I have been trying to use this code:
Code: Select all
<?php
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
// Add item to the end of the $_SESSION['cart'] array
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF'] . '?' . SID);
exit();
}
However this is where i get lost... i don't know how to make a view cart which will then display the name of the product and the price and create a total. I've tried numerous tutorials and now my head is about to explode lol!!
Here is some view cart code i found which uses arrays:
Code: Select all
<?php
session_start();
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if (isset($_GET['empty'])) {
// Empty the $_SESSION['cart'] array
unset($_SESSION['cart']);
header('location: ' . $_SERVER['PHP_SELF'] . '?' . SID);
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Shopping cart</title>
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Your Shopping Cart</h1>
<?php
$items = array(
'Canadian-Australian Dictionary',
'As-new parachute (never opened)',
'Songs of the Goldfish (2CD Set)',
'Ending PHP4 (O\'Wroxey Press)');
$prices = array( 24.95, 1000, 19.99, 34.95 );
?>
<table border="1">
<thead>
<tr>
<th>Item Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
$total = 0;
for ($i = 0; $i < count($_SESSION['cart']); $i++) {
echo '<tr>';
echo '<td>' . $items[$_SESSION['cart'][$i]] . '</td>';
echo '<td align="right">$';
echo number_format($prices[$_SESSION['cart'][$i]], 2);
echo '</td>';
echo '</tr>';
$total = $total + $prices[$_SESSION['cart'][$i]];
}
?>
</tbody>
<tfoot>
<tr>
<th align="right">Total:</th><br>
<th align="right">$<?php echo number_format($total, 2); ?></th>
</tr>
</tfoot>
</table>
<p><a href="catalog.php">Continue Shopping</a> or
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?empty=1">Empty your cart</a></p>
</body>
</html>
Thanks
C