php - Storing multiple items into a session

638

I am trying to store multiple items into a session. I am posting an items from a form like so:

<?php
$product_id = $_GET['product_id'];
$sql = "SELECT * FROM Products WHERE product_id = $product_id";
  $result = $conn->query($sql);

  if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
      echo '<img src=' . $row['product_img'] . ' />';
      echo '<div >'. $row['product_name'] .'</div>';
      echo '<div >'. $row['product_price'] .'</div>';
      echo '<div >'. $row['product_sku'] .'</div>';
      echo '<div >'. $row['product_description'] .'</div>';
      echo '<form action="addToCart.php" method="post">
          <input type="hidden" name="product_img" value="' . $row['product_img'] . '" />
          <input type="hidden" name="product_id" value="' . $row['product_id'] . '" />
          <input type="hidden" name="product_name" value="' . $row['product_name'] . '" />
          <input type="hidden" name="product_price" value="' . $row['product_price'] . '" />
          <input type="hidden" name="product_sku" value="' . $row['product_sku'] . '" />
          <input type="hidden" name="product_description" value="' . $row['product_description'] . '" />
          <input type="submit" name="Submit">
         </form>';
    }
  } else{
  echo "0 Results";
  }
?>

addToCart.php looks like this:

<?php 
    if (isset($_POST['Submit'])) { 
        $_SESSION['product_img'] = $_POST['product_img'];
        $_SESSION['product_id'] = $_POST['product_id'];
        $_SESSION['product_name'] = $_POST['product_name'];
        $_SESSION['product_price'] = $_POST['product_price'];
        $_SESSION['product_sku'] = $_POST['product_sku'];
        $_SESSION['product_description'] = $_POST['product_description'];
    } 
?>

So the above is now setting the items into the session (So I believe). I am then outputting the item from the stored data in basket.php

<?php echo '<img src=' . $_SESSION['product_img'] . ' />'; ?>
<?php echo $_SESSION['product_id'];?>
<?php echo $_SESSION['product_name'];?>
<?php echo $_SESSION['product_price'] ?>
<?php echo $_SESSION['product_sku']; ?>
<?php echo $_SESSION['product_description']; ?>

the Issue I have is whenever I add another item it overrides the previous item? I know I need to use an array to store multiple items but I have tried a few different things but I am struggling to understand.

777

Answer

Solution:

You can use [] to store them in array:

$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description']

Now, try to see what are in each array:

var_dump($_SESSION['product_id']);
456

Answer

Solution:

It is possible to store your Session Data as nested array. In your case, since it is a Shopping Cart, you may want to build your Arrays using the ID of the Product; that way you are certain that no product will override the other (so long as they don't have the sameproduct_id values.... Below is an example of how you may do that:

<?php   
    //FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
    if (session_status() == PHP_SESSION_NONE  || session_id() == '') {
        session_start();
    }
    if (isset($_POST['Submit'])) {
        $product_id             = htmlspecialchars(trim($_POST['product_id']));
        $product_img            = htmlspecialchars(trim($_POST['product_img']));
        $product_sku            = htmlspecialchars(trim($_POST['product_sku']));
        $product_name           = htmlspecialchars(trim($_POST['product_name']));
        $product_price          = htmlspecialchars(trim($_POST['product_price']));
        $product_description    = htmlspecialchars(trim($_POST['product_description']));

        if(!isset($_SESSION['products'])){
            $_SESSION['products'] = array();
        }
        if(!isset($_SESSION['products'][$product_id])){
            $_SESSION['products'][$product_id] = array();
        }
        $_SESSION['products'][$product_id]['product_id']            = $product_id;
        $_SESSION['products'][$product_id]['product_img']           = $ $product_img;
        $_SESSION['products'][$product_id]['product_name']          = $product_name;
        $_SESSION['products'][$product_id]['product_price']         = $product_price;
        $_SESSION['products'][$product_id]['product_sku']           = $product_sku;
        $_SESSION['products'][$product_id]['product_description']   = $product_description;     
    } 

And anywhere else (another Script perhaps) you could access your Data like so:

<?php

    $output             = "";
    $storedProductData  = $_SESSION['products'];
    if(!empty($storedProductData)){
        foreach($storedProductData as $product_id=>$productData){
            $output .= "<img src='{$productData['product_img']}' />"                            . PHP_EOL;
            $output .= "<span id='generic-class'>{$productData['product_id']}</span>"           . PHP_EOL;
            $output .= "<span id='generic-class'>{$productData['product_name']}</span>"         . PHP_EOL;
            $output .= "<span id='generic-class'>{$productData['product_price']}</span>"        . PHP_EOL;
            $output .= "<span id='generic-class'>{$productData['product_sku']}</span>"          . PHP_EOL;
            $output .= "<span id='generic-class'>{$productData['product_description']}</span>"  . PHP_EOL;
        }
    }

People are also looking for solutions to the problem: php - PHP_RELEASE_VERSION on PHP7 shows 6 instead of 7

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.