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?

4
  • 1
    Did you start session when you added product to your cart? Commented Nov 24, 2015 at 12:34
  • at this point you should have your debugging on. Try to provide more details. is this a one page script? Commented Nov 24, 2015 at 12:35
  • you need use @session_start(); before you can print_r($_SESSION['cart'],1); Commented Nov 24, 2015 at 12:36
  • Add session_start() at the beginning of your script. Commented Nov 24, 2015 at 12:37

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.