I'm writing a shopping cart from scratch. To save my variables from script to script, I've decided to define a session array. Here is the defintion:

$_SESSION["product"] = array(
"model" => $model,
"qty" => $qty,
"price" => $price,
"color" => $color1,
"image" => $image
);

I'm passing the variables from a previous script that shows the catalog. I want to be able to update the array dynamically each time a new product is added to the shopping cart, but I'm having trouble with the code. I guess I'm using this array as kind of a record and I want to be able to address each 'record' and print it out.

I know I can also write a user file to the MySQL database and I will do that if I can't get my code resolved. I don't want to use cookies since a lot of people have cookies turned off.

Or should I just use a multi-dimensional array?

Thanks for any help you can give me.

    I think you need to use one more array level for your approach to work.

    So you'd have $SESSION['product'] = array() and then $SESSION['product'][0] = array("model" => $model, [etc...]);. Then the second product in the cart would be like: $_SESSION['product'][0] = array("model" => $model, [etc...]); Essentially, a 3 dimensial array. Kind of ugly if you ask me, but should work.

    I'd lean towards keeping a cart ID and tossing the cart contents in the DB - you could do some tracking this way too as to how many times product X was in the cart but not purchased, for example

      Instead of having an associative array with fixed keys, consider using objects instead. It'll let you do the same thing, and allow you to add methods later on if you want.

      class Product {
          var $model;
          var $qty;
          var $price;
          var $color;
          var $image;
      }
      
      $_SESSION['products'] = array();
      
      $product =& new Product();
      $product->model = 'Superconfabulator 1000';
      $product->qty = 1;
      $product->price = 19999.99;
      $product->color = 'Navy blue w/ gold sparkles';
      $product->image = '/images/superconfab1000.jpg';
      
      $_SESSION['products'][] =& $product;
      
        Write a Reply...