Page 1 of 1

Session Variables as an Array

Posted: Wed Jul 18, 2007 5:39 am
by NotOnUrNelly
Hi all,

Im doing an assignment for university that requires me to set up a simple shopping cart mechanism.

I have 2 pages currently the items list page, that has items with buttons.

Once the button is clicked the cartaction page is called and I am adding the recieved item name into separate session variables of the name sent as seen below

Code: Select all

$item = $_REQUEST['item'];
//echo $item;
switch ($item) {
case "coppercasserole":
   $HTTP_SESSION_VARS['coppercasserole'] = $HTTP_SESSION_VARS['coppercasserole'] + 1;
 //  echo "copperCasserole =".$HTTP_SESSION_VARS['coppercasserole'];
    break;
case "coppersaucepan":
$HTTP_SESSION_VARS['coppersaucepan'] = $HTTP_SESSION_VARS['coppersaucepan'] + 1;
//   echo "coppersaucepan =".$HTTP_SESSION_VARS['coppersaucepan'];
    break;
	case "coppersaute":
$HTTP_SESSION_VARS['coppersaute'] = $HTTP_SESSION_VARS['coppersaute'] + 1;
//   echo "coppersaute =".$HTTP_SESSION_VARS['coppersaute'];
    break;
}
This is working fine because each sessionvariable takes the name of the item. Then if the item is added again the value of the session variable is incremented.

Is there a better way of doing this using an array in the session variable. I not quite sur eon how this would work.

Thanks
Jamie

Posted: Wed Jul 18, 2007 6:27 am
by Gente
What about this?

Code: Select all

if (!isset($_SESSION[$item]))
{
  $_SESSION[$item] = 0;
}
$_SESSION[$item] = $_SESSION[$item] + 1;

Posted: Wed Jul 18, 2007 6:55 am
by NotOnUrNelly
Thanks for your reply

Uhm,

Not sure how that would work,

What I am thinking is

session(cart)[typea][1]
[typeb][5]
[typec][9]

where the second number is the quantity added to the cart.

I'm ust not sure on how to do it.

Posted: Wed Jul 18, 2007 7:06 am
by Gente
NotOnUrNelly wrote:Thanks for your reply

Uhm,

Not sure how that would work,

What I am thinking is

session(cart)[typea][1]
[typeb][5]
[typec][9]

where the second number is the quantity added to the cart.

I'm ust not sure on how to do it.
And how do you propose to get the numbers of for example 'typea' this way?
It's now a problem to make the array you posted. The question is 'what for?'.

Posted: Wed Jul 18, 2007 10:50 am
by pickle
I think you're right to want to put these in an array. Its a simple matter of just adding another index when you're updating the count. Also, $HTTP_SESSION_VARS is deprecated in favour of $_SESSION.

Code: Select all

$item = $_REQUEST['item'];
switch($item)
{
  case 'coppercasserole':
    $_SESSION['items']['coppercasserole']++;
    break;
  case 'coppersaucepan':
    $_SESSION['items']['coppersaucepan']++;
    break;
  case 'coppersaute':
    $_SESSION['items']['coppersaute']++;
    break;
}