简体   繁体   中英

Store array in session variable and post the session variable into another page

This is my code in 1st page,

<?php
session_start();
require 'dataconnection.php';
$res = mysql_query("select * from questions where category_id=1 LIMIT 20") or die(mysql_error());
$rows = mysql_num_rows($res);

echo $rows;

while ($result=mysql_fetch_assoc($res)) {
    for($i=1;$i<=$rows;$i++)
    {           
        $_SESSION['questions']=$result;

    }
    echo implode("",$_SESSION['questions']);

}
?>

In next page my code

<?php    
session_start();    
echo implode(",",$_SESSION['questions']);
?>

This part of the code doesn't add to an array, but overwrite the value in it. It simply sets $_SESSION['questions'] to the same value as $result x times, where x is the number of rows.

while ($result=mysql_fetch_assoc($res)) {
  for($i=1;$i<=$rows;$i++)
  {           
    $_SESSION['questions']=$result;
  }
}

Try changing it to:

while ($result=mysql_fetch_assoc($res)) {         
    $_SESSION['questions'][]=$result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM