tags:

views:

49

answers:

3

I am writing a script in php, which is quite similar to a shopping cart. what i want to do is when a users adds a certain product i need to add the productid to a session variable,without storing in a database. so each time the user adds a product the productid needs to be stored in a session variable.

and when the user checkouts i need to retrieve all the productids and display?

can some one please explain me how to do it? coz im fine with 1 product but not sure how to store and retrieve multiple values.

any help will be much appreciated

+7  A: 

Place an Array in the Session. Add the items to the array.

$_SESSION['cart'] = array();
$_SESSION['cart'][] = $apples;
$_SESSION['cart'][] = $oranges;
$_SESSION['cart'][] = $pears;

Note: replace $apples, $oranges and $pears with your product ids.

You access the array like any other array in PHP, e.g. to count the items:

echo count($_SESSION['cart']);

and to iterate over the items:

foreach($_SESSION['cart'] as $item)
{
    echo $item;
}

You could also wrap the Session into an object and provide access to the cart through a method interface, but I leave that for someone else to explain.

Gordon
Then you can use `count($_SESSION['cart'])` to count how many items in your cart. Use `foreach` on `$_SESSION['cart']` to loop through each item to display
Axsuul
it's probably worth saving the session to a database and then if the customer leaves the site before completions or times out you can retrieve the cart from the db and set it back as a session.
PurplePilot
$_SESSION['cart'] = array(); is not needed.
useless
@user267351 True. I'll leave it for verbosity, but thanks for pointing it out.
Gordon
While $_SESSION['cart']=array() is not strictly required, it is generally good practice to declare variables before using them.
Alex JL
+2  A: 

Each session is an associative array. You can store other arrays in it, like

$_SESSION['products']=array();
$_SESSION['products'][]='123123'
$_SESSION['products'][]='cow_34526'

and then you can work with this as with any other array, i.e.

foreach($_SESSION['products'] as $item){
  //display or process as you wish
  }
Alex JL
+2  A: 

Put the following in a file called index.php and give it a test:

<?php
session_start();
if(isset($_POST['product'])) {
    $products = isset($_SESSION['products']) ? $_SESSION['products'] : array();
    $products[] = $_POST['product'];
    $_SESSION['products'] = $products;
}
?>

<html>
    <body>
        <pre><?php print_r($_SESSION); ?></pre>
        <form name="input" action="index.php" method="post">
            <input type="text" name="product" />
            <input type="submit" value="Add" />
        </form> 
    </body>
</html>
Bart Kiers
Thank you very much
LiveEn