Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

Store mySQLi array in PHP session?

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 
";
}

/*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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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 
";
}

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'];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...