0

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;

}

2
  • 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 Commented Apr 30, 2014 at 23:14
  • Thanx alot sir for your help. Ill check this out and will let u know Commented Apr 30, 2014 at 23:17

1 Answer 1

3

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 />';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Manolis Agkopian : thanx alot it worked. I was been stuck on this issu since the last couple of days but finally it has been resolved..thanx alot sir :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.