我想在一个文件中执行查询,将其存储在会话变量中,并在另一个文件中访问结果。
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>";
}
关于我做错了什么的任何想法?或者,还有另一种方法来完成我在这里要做的事情吗?
答案 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)
你有两个问题:
__sleep()
和__wakeup()
,以便您可以选择如何序列化对象 - 您将在序列化中包含哪些成员,以及在反序列化时如何重新初始化其他成员 - 还要记住,当unserualiza
此类对象时,必须定义对象的类如前所述,您的最终解决方案将获取行并将其保持在会话中。如果你不想保留行(你告诉他们只有一行,但也许你不想要一个渴望获取),保留一个数组来定义和再次绑定查询。