Page 1 of 1
I need help with session variables
Posted: Thu Sep 29, 2005 2:11 am
by vigour
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.
Posted: Thu Sep 29, 2005 2:30 am
by mickd
Code: Select all
session_start();
$value = 'valueinsession';
$_SESSION['name'] = $value;
echo $_SESSION['name'];
session_destroy();
Posted: Thu Sep 29, 2005 3:44 am
by shiznatix
remember that for each page that you want to use a session you have to put session_start() at the top of the page
Posted: Thu Sep 29, 2005 3:53 am
by vigour
mickd wrote: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.
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'][];
This only outputs the word array. I want to put many $item arrays into the session basket and then echo them out from session basket. Yes I know I probably need a loop to do this, but I can't echo out anything at all except the word array.
Posted: Thu Sep 29, 2005 4:03 am
by Jenk
Ok, the problem is with the line:
Code: Select all
<?php
echo $_SESSION['basket'][];
?>
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
foreach ($_SESSION['basket'] as $item) {
print ("
Product Code: {$item['ProductCode']}
Description: {$item['Description']}
Price: {$item['Price']}
Quantity: {$item['Quantity']}
\n\n");
}
?>
Posted: Thu Sep 29, 2005 6:11 am
by vigour
Thanks, works very nice.
Posted: Thu Sep 29, 2005 8:01 am
by dude81
Posted: Thu Sep 29, 2005 8:07 am
by mickd
print_r should also display the information but it wont be in a very neat way like
Code: Select all
foreach ($_SESSION['basket'] as $item) {
print ("
Product Code: {$item['ProductCode']}
Description: {$item['Description']}
Price: {$item['Price']}
Quantity: {$item['Quantity']}
\n\n");
}
would.