0
votes

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,product quantity and product size to a session array,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 my array just shows 1 product but not all.

i have also read a post on this platform but that also didnt cux again its storing only variable.. link of that post

[link] (store mutiple values in php session)

Thanx in advance for help.

Code That I Tried:

 $cart=array("p_id"=>"$_SESSION[productid]",
             "p_size"=>"$_SESSION[p_size]",
             "p_qty"=>"$_SESSION[p_qty]");

 $_SESSION["cart"]=$cart;


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

}

1
You need a multi dimensional array to do this - i.e. it can store multiple array objects inside of it to correspond to each product added to the cart. webcheatsheet.com/php/multidimensional_arrays.php - adaam
Thanx alot sir for your help. Ill check this out and will let u know - Ali Muhammad

1 Answers

3
votes

Your are overwriting the last product in the cart. Instead of $_SESSION["cart"]=$cart; do $_SESSION["cart"][]=$cart;

$cart = array (
    'p_id' => $_SESSION['productid'],
    'p_size' => $_SESSION['p_size'],
    'p_qty' => $_SESSION['p_qty']
);

$_SESSION['cart'][] = $cart;


foreach ($_SESSION['cart'] as $item) {
    echo 'p_id: ', $item['p_id'], '<br />';
    echo 'p_size: ', $item['p_size'], '<br />';
    echo 'p_qty: ', $item['p_qty'], '<br /><br />';
}