Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

store mutiple values in php session

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...