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 ad开发者_StackOverflowds 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
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.
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
}
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>
$role=json_encode($checkUser1[0]);
$role2=str_replace('"','',$role);
$company=json_encode($checkUser2[0]);
$company=str_replace('"','',$company);
$_SESSION['LOGIN_STATUS']=true;
$_SESSION['UNAME']=$uname;
$_SESSION['datefrmt']='dd/mm/yy';
$_SESSION['role']=$role2;
$_SESSION['company']=$company;
精彩评论