I need help with session variables
Moderator: General Moderators
I need help with session variables
I'm trying to understand session variables. I want to use them in a shopping basket to hold the items. But I do not know how, can someone please give me a easy example how to start the session, put data in it, delete data from it and echo data from it.
Code: Select all
session_start();
$value = 'valueinsession';
$_SESSION['name'] = $value;
echo $_SESSION['name'];
session_destroy();Thanks, that's a good start. But if I want to do this.mickd wrote:Code: Select all
session_start(); $value = 'valueinsession'; $_SESSION['name'] = $value; echo $_SESSION['name']; session_destroy();
Code: Select all
// start session
session_start();
// make up item to go in shopping basket
$item = array();
$item['ProductCode'] = "1";
$item['Description'] = "Car";
$item['Price'] = 240;
$item['Quantity'] = 1;
// add item to end of shopping basket
$_SESSION['basket'][] = $item;
// echo it out
echo $_SESSION['basket'][];Ok, the problem is with the line:
When you refer to an array and use [] on the end (i.e. no indice specified) that creates a new indice, thus it will appear empty.
If you want to echo what the Basket contains, you'll need to use a loop, such as the following:
Code: Select all
<?php
echo $_SESSION['basket'][];
?>If you want to echo what the Basket contains, you'll need to use a loop, such as the following:
Code: Select all
<?php
foreach ($_SESSION['basket'] as $item) {
print ("
Product Code: {$item['ProductCode']}
Description: {$item['Description']}
Price: {$item['Price']}
Quantity: {$item['Quantity']}
\n\n");
}
?>I hope this also works
Code: Select all
print_r($_SESSION['basket'])print_r should also display the information but it wont be in a very neat way like
would.
Code: Select all
foreach ($_SESSION['basket'] as $item) {
print ("
Product Code: {$item['ProductCode']}
Description: {$item['Description']}
Price: {$item['Price']}
Quantity: {$item['Quantity']}
\n\n");
}