-2

How do you store mySQLi array in PHP session? I used while loop to render out the array but how should I assign each of them to the session?

Here is my attempt:

while($row = mysqli_fetch_array($sqlCommand)){ 
             $id = $row["id"];
             $product_name = $row["product_name"];
             $price = $row["price"];
             $all_list .= "id= $id, product name = $product_name, price = $price \n";
}

/*only work if only LIMIT  1*/
//$_SESSION["id"] = $id;
//$_SESSION["product_name"] = $product_name;
//$_SESSION["price"] = $price;

I have also tried to assign session variable to each of the array however it only works if the result is limited to one. In my case the result will be at least one or more. How can I do that?

Vincent1989
  • 1,593
  • 2
  • 13
  • 25
  • Uh, what? your id, prdouct name and price variables are overwritten with each loop through the while clause, the only thing that 'stores' everything is the all variable. – Epodax Nov 20 '15 at 11:15
  • Possible duplicate of [store mysqli\_query result in session](http://stackoverflow.com/questions/29611072/store-mysqli-query-result-in-session) – davejal Nov 20 '15 at 11:18

1 Answers1

3
while($row = mysqli_fetch_array($sqlCommand)){ 
             $_SESSION[]['id'] = $row["id"];
             $_SESSION[]['product_name'] = $row["product_name"];
             $_SESSION[]['price'] = $row["price"];
             $_SESSION[]['all_list'] .= "id= $id, product name = $product_name, price = $price \n";
}

Will store all rows as an array in your session.

To look at the result use the following line after the while loop: var_dump($_SESSION);

To access a specific value (for example id) use the following: echo $_SESSION[0]['id'];

AgeDeO
  • 3,137
  • 2
  • 25
  • 57