By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,627 Members | 2,339 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,627 IT Pros & Developers. It's quick & easy.

use $_SESSION[$variable] instead of $_SESSION['whatever'] ?

P: 2
Hi

Really dumb problem that's got me beat. Can someone help.

The prolem: I'm trying to count the number of times an item has been clicked. There are many items. I want to create a session variable for each item as its clicked, and increment the value held by the session variable by 1 each time that item is clicked. My plan was to allow an item to be selected on one page - when a user selects an item, a numeric value will be passed to a second page by means of the querystring .... ?item=5.

Here is the second page where I try to deal with it...

[PHP]<?php

session_start();

$item = $_GET['item'];

if (isset($_SESSION[$item]))
{
//increment the number to times this item has been selected by 1.
$_SESSION[$item] = $_SESSION[$item] + 1;
}
else
{
//This is the first time this item has been selected. Set value to 1.
$_SESSION[$item] = 1;
}

echo "Item ".$item." has been selected ".$_SESSION[$item]." times";
//e.g Item 5 has been selected 14 times
?>[/PHP]


Can anyone see what I'm doing wrong. The session doesn't set, so item 5 (or any other item) always comes back as being clicked 1 time.

Thanks
Shaz


P.S. I also tried using a session array(?), but no joy there either:

[PHP]<?php

session_start();

$_SESSION['test'] = array();
$item = $_GET['item'];

if (isset($_SESSION['test'][$item]))
{
//increment the number to times this page has been selected by 1.
$_SESSION['test'][$item] = $_SESSION['test'][$item] + 1;
}
else
{
//This is the first time this page has been selected before. Set value to 1.
$_SESSION['test'][$item] = 1;
}

echo "Item ".$item." has been selected ".$_SESSION['test'][$item]." times";
//e.g Item 3 has been selected 14 times


?>[/PHP]
Mar 8 '08 #1
Share this Question
Share on Google+
2 Replies


P: 2
Scrub that. I got it sussed all by myself :)

I was almost there second time round. I moved the line that sets the session up as an array to its own page - e.g. page 0. Now it all work.

Thanks!
Mar 8 '08 #2

ronverdonk
Expert 2.5K+
P: 4,258
Good you found it yourself. See you next time.

Ronald
Mar 9 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.