Page 1 of 1

Array Cart

Posted: Sun Jun 22, 2003 7:16 am
by Zeceer
I'm trying to make this cart script, that is adding products and the quantity for the product. It then saves the array in a session, and when the customer at a later point adds a new item the script checks if session is allready set. If it is it continues with that array, just adding a new product.

The problem is that if there aren't any products stored in the array it doesn't work, and if there are 1 product in it, it want add more than one.

Script:

Code: Select all

<?php
session_start();

$product = $_GET['id'];

if( empty($HTTP_SESSION_VARS['cart']) )
{
    $cart="array()";
    $current_items="0";
}
else
{
    $cart = $HTTP_SESSION_VARS['cart'];
    $current_items= $HTTP_SESSION_VARS['current_items'];
}

//Adding the new product

$cart[$current_items]['product'] = "$product";
$cart[$current_items]['quantity'] = "1";
$current_items++;

session_register("cart");
session_register("current_items");

//Looping thru the array

foreach( $cart as $temp )
{
    foreach( $temp as $key=>$final_val )
    {
        print("$key: $final_val<br>");
    }
    print("<br>");
}

?>
mod_edit: changed to

Code: Select all

tags[/size]

Posted: Sun Jun 22, 2003 8:22 am
by volka
$cart="array()";
this makes $cart a string-variable containing the string array().
$cart=array(); makes it an empty array.
Why not simply testing the existence of that entry with isset()? An empty array is is_empty() but it is set, therefor isset() will return true.

Posted: Sun Jun 22, 2003 8:37 am
by Zeceer
I don't really get it :oops: Could you show me how in the script above?

Posted: Sun Jun 22, 2003 8:56 am
by volka

Code: Select all

if( !isset($HTTP_SESSION_VARS['cart']) )
{
    $cart=array();
    $current_items=0;
}
else
{
    $cart = $HTTP_SESSION_VARS['cart'];
    $current_items= $HTTP_SESSION_VARS['current_items'];
}

Posted: Sun Jun 22, 2003 12:00 pm
by Zeceer
I've done some cofiguration. Have I see it, the script will now register "cart" and "current_items" if they are not set. The script will then use these session variables to add the new item. But I just get an errorsaying that "cart" and "current_items" doesn't exist.

Code: Select all

<?php
session_start();

$product = $_GET&#1111;'id'];

if( ! isset($HTTP_SESSION_VARS&#1111;'cart']) && isset($HTTP_SESSION_VARS&#1111;'cart']) )
&#123;
    session_register("cart");
    session_register("current_items");
&#125;

$cart = $HTTP_SESSION_VARS&#1111;'cart'];
$current_items = $HTTP_SESSION_VARS&#1111;'current_items'];

//Adding the new product

$cart&#1111;$product]&#1111;'product'] = "$product";
$cart&#1111;$product]&#1111;'quantity'] = "2";
$current_items++;

//Looping thru the array

foreach( $cart as $temp )
&#123;
    foreach( $temp as $key=>$final_val )
    &#123;
        print("$key: $final_val<br>");
    &#125;
    print("<br>");
&#125;

?>