1

Please check the following code below i am trying to achieve a Session based Cart system for my site:

This is what happens when i post the form:

session_start();
if (isset($_POST['addtocart'])):
$item = array(
  'package' => $_POST['item_name'],
  'amount' => $_POST['amount']
);
$_SESSION['cart'][] = $item;
endif;

Then the data is like this:

array(2) {
  [0]=>;
  array(2) {
    ["package"]=>;
    string(42) "Bronze (Division V) ->; Bronze (Division V)"
    ["amount"]=>;
    string(1) "0"
  }
  [1]=>;
  array(2) {
    ["package"]=>;
    string(46) "Bronze (Division V) ->; Challenger (Challenger)"
    ["amount"]=>;
    string(4) "1666"
  }
}

and i am trying to display data like this:

foreach ($_SESSION['cart'] as $item):
    echo $item->package;
endforeach;

The result is nothing so what did i do wrong here?

2 Answers2

1

You are storing the package as an array item and trying to retrieve it as an object property.

So try changing this line

echo $item->package; 

To

 echo $item['package'];

Your current code should be throwing an error, Something along the lines of

Warning: PHP Notice: Undefined property: stdClass::$package
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • This might be it, I have debugging off since its WordPress at the moment. But the above does make sense. Is the code I have the best solution or do you recommend a different method? –  Nov 24 '15 at 12:41
  • If you only want to use the `$_SESSION` to store the input variables then your method looks ok, IMHO. Also its highly likely that the "debugging mode off" is suppressing the warnings. – Mohd Abdul Mujib Nov 24 '15 at 12:45
0

As @davejal mentioned you should turn some debugging options on to get more error details while developing. How to do so can be read here: https://stackoverflow.com/a/845025/3948598

You need to enable error display in the php.ini.

Check this page in the PHP documentation for information on the 2 directives: error_reporting and display_errors. display_errors is probably the one you want to change.

Community
  • 1
  • 1
Minzkraut
  • 2,149
  • 25
  • 31
  • sorry for that, wen't to fast on this one. still you should consider turning the display of errors on as i mentioned in my edit – Minzkraut Nov 24 '15 at 12:41