store products in $_session

Discussion in 'PHP' started by novakrog, Nov 28, 2008.

  1. #1
    I am new to the forum.
    I throughly appreciate your help with some code about my problem solving. I designed shopping cart using:

    1. product link - code:
    //customer data will be stored into $_SESSION
    session_start();
    $_SESSION['productsid'] = $row["productid"];
    $_SESSION['prices'] = $row["price"];

    // session data will be transferred via form to:
    shoppingcart.php link


    2. shopping cart link – code:

    // I add some variables for the product’s id and price info and echo them
    session_start();
    $productid = $_SESSION['productsid'];
    $prices = $_SESSION['prices'];
    echo "$productid";
    echo "$prices";

    I tested and this works ok, but my main problem is that I dont know how to transfer more product(s) than one and present all stored in the session. So far I can present only one product.

    I tested this:
    After presenting the product from the session of the shopping card code, I stored a new product in the session (product link – code). The shopping card link presented the new one product but not the old one. Do I have to use some increment multi-dimensional arrays or similar ?

    Can you help me with some code description?
    Thank you very much for your help!
     
    novakrog, Nov 28, 2008 IP
  2. misbah

    misbah Active Member

    Messages:
    265
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    68
    #2
    try this
    your product.php
    session_start();
    $_SESSION['productsid'] = ($_SESSION['productsid'] != '') ? $_SESSION['productsid'] . '|' . $row["productid"] : $row["productid"];
    $_SESSION['prices'] = ($_SESSION['prices'] != '') ? $_SESSION['prices'] . '|' . $row["price"] : $row["price"];
    PHP:
    and your shoppingcart.php
    session_start();
    $productid = explode('|', $_SESSION['productsid']);
    $prices = explode('|', $_SESSION['prices']);
    print_r("$productid");
    print_r("$prices");
    PHP:
     
    misbah, Nov 28, 2008 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    I would personally store the session data as an array. I would most likely format it something like this:

    $_SESSION['cart'][] = array('product_id'=>$product_id, 'product_qty'=>$product_qty, 'product_price'=>$product_price);

    Every item they add, you can set another $_SESSION['cart'][] array. You can later loop through them all to get a total or to display the entire cart.
     
    jestep, Nov 28, 2008 IP