使用PHP SESSION Variables存储MySQL查询结果

时间:2014-07-21 20:46:58

标签: php mysql mysqli session-variables

我想在一个文件中执行查询,将其存储在会话变量中,并在另一个文件中访问结果。

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

关于我做错了什么的任何想法?或者,还有另一种方法来完成我在这里要做的事情吗?

2 个答案:

答案 0 :(得分:1)

将实际数组存储在会话中:

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);

答案 1 :(得分:1)

你有两个问题:

  1. 尝试存储类实例就像他们告诉你的那样(请记住,该类应该实现__sleep()__wakeup(),以便您可以选择如何序列化对象 - 您将在序列化中包含哪些成员,以及在反序列化时如何重新初始化其他成员 - 还要记住,当unserualiza此类对象时,必须定义对象的
  2. 尝试存储,尤其是myqsli对象。这些对象包含对可以收集的资源的引用,因此即使您成功序列化这样的对象,它们的内部引用也不再有效。
  3. 如前所述,您的最终解决方案将获取行并将其保持在会话中。如果你不想保留行(你告诉他们只有一行,但也许你不想要一个渴望获取),保留一个数组来定义和再次绑定查询。