Using PHP SESSION Variables to store MySQL query r

2019-03-04 07:30发布

问题:

This question already has an answer here:

  • Can I store a class instance in a $_SESSION space? 4 answers

I want to execute a query in one file, store it in a session variable, and access the result in another file.

File1.php:

//This is the file I have executed my sql statement in
//I have already done session_start(); and initialized $conn
$query = //my query. I know it is working because I have tested it elsewhere, so I 
         // don't believe it is the problem
$_SESSION['query2'] = mysqli_query($conn, $query)

File2.php:

//This is the file I want to access my query results in.
//I have already done session_start(); and initialized $conn

$tempArray =  $_SESSION['query2'];

if (isset($tempArray)) {
    $row = mysqli_fetch_array($tempArray, MYSQL_NUM);
    if ($row == null) {
        echo "<h1> error </h1>"; //This line gets executed
    } else {
        echo "<h1> works! </h1>";
    }
} else {
    echo "<h1> array not set </h1>";
}

Any ideas as to what I am doing wrong? Or, is there another way to accomplish what I'm trying to do here?

回答1:

Store the actual array in session:

File1.php:

$query = //my query. 
$result = array();
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($res, MYSQL_NUM){
    $result[] = $row;
}
$_SESSION['query2'] = $result;

File2.php:
//I have already done session_start(); and initialized $conn

$tempArray =  $_SESSION['query2'];
var_dump($tempArray);


回答2:

You have two problems there:

  1. Trying to store a class instance is as they told you (remember that the class should implement __sleep() and __wakeup() so you can choose how to serialize the object - what members will you include in serialization, and how will you re-initialize other members when you deserialize - also remember that the object's class must be defined when you unserualiza such object).
  2. Trying to store, particularly, a myqsli object. Those objects contain references to resources which can be collected, so even if you successfully serialize-back such object, their internal references could not be valid anymore.

Your end solution will be, as said before, fetching the rows and keeping them in session. If you don't want to keep the rows (you told there's only one row, but perhaps you don't want an eager-fetching), keep an array with the data to define and bind the query again.