Hi all,
Any ideas how to get the following working? I'm creating a shopping cart and are having trouble getting the items into a session array.
Lets say i have a form like:
<form action="cart/addtocart.php" method="post">
<INPUT name="image2" type=image src="images/add_to_cart_btn.gif" alt="Add to Cart" width="82" height="17" border=0>
<input name="movie_id" type="hidden" value="<? echo $movie_id ?>">
</form>
The movie_id value gets taken to the addtocart.php script which looks like:
<?php
ob_start();
session_start();
include ('functions.php');
if (!empty($_POST['movie_id'])) {
// Really should do some checking here because otherwise people can just
// enter stuff in from the url and cause no end of problems
$movie_id = $_POST['movie_id'];
// Starting a new cart session
if (!session_is_registered("cart")) {
$_SESSION['cart'] = array();
$_SESSION['items'] = 0;
$_SESSION['total_price'] = 0.00;
}
// Existing book in the cart + 1
if (!isset($_SESSION['cart'][$movie_id])) {
$_SESSION['cart'][$movie_id]++;
}
else {
$_SESSION['cart'][$movie_id] = 1;
}
$_SESSION['total_price'] = calculate_price($_SESSION['cart']);
$_SESSION['items'] = calculate_items ($_SESSION['cart']);
header ("Location: ./");
}
ob_end_flush();
?>
The include file functions.php looks like:
<?PHP
function calculate_price($cart)
{
$_SESSION['price']=0.0;
if(is_array($_SESSION['cart']))
{
$connection=mysql_connect("","","") or die('Could not connect to the database server');
$db = mysql_select_db("db_swif_flix", $connection) or die ("Unable to select database.");
foreach($_SESSION['cart'] as $isbn => $qty)
{
$sql= "SELECT
movie_current_price
FROM
movie
WHERE
movie_id='$isbn'";
$sql_result = mysql_query($sql,$connection) or die ("Could not select data");
while ($row = mysql_fetch_row($sql_result))
{
$_SESSION['movie_current_price']= $row['0'];
}
$_SESSION['price'] += $_SESSION['movie_current_price']*$qty;
}
}
return $_SESSION['price'];
}
function calculate_items($cart)
{
$_SESSION['items']=0;
if(is_array($_SESSION['cart']))
{
foreach($_SESSION['cart'] as $movie_id => $qty)
{
$_SESSION['items'] += $qty;
}
}
return $_SESSION['items'];
}
?>
After the addtocart.php does it's processing it displays the results on the index.php page.
This is an abbreviated version of that page:
<?
session_start();
if ($_SESSION['cart']) {
foreach ($_SESSION['cart'] as $isbn => $qty){
echo "$isbn<br>";
echo $_SESSION['total_price'];
}
} else {
echo "No cart array!";
}
?>
The result i get is "No cart array!".
Can anyone see how i can get this to add the items to the cart?
Cheers,
micmac