数据库
首页 > 数据库> > PHP-在会话中存储mysqli_query结果

PHP-在会话中存储mysqli_query结果

作者:互联网

我想将MySQLi查询的结果存储为会话变量,以便可以重用它而无需再次执行查询.我不想在我网站的每个页面上或每次刷新页面时都执行相同的查询.

我已经尝试过下面的代码,但是出现类似“对象不能存储在会话中”和“ mysqli_fetch_array期望参数1为资源”之类的错误.

如何在会话中存储查询结果?

session_start();

if (!isset($_SESSION['query_result'])) {
    $anything=mysqli_query($connection,"select something from table name 
        where filed1='$variable' order by id desc limit 70");
    $_SESSION['query_result']=$anything;
} else {
    $anything= $_SESSION['query_result'];
}

while ($data=mysqli_fetch_array($anything)) {
    /* output the data */
}

解决方法:

尝试这个:

  if(!isset($_SESSION['query_result'])){
     $anything=mysqli_query($connection,"select something from table name where filed1='$variable' order by id DESC limit 70");
     while($res = mysqli_fetch_row($anything)){
        array_push($_SESSION['query_result'], $res);
     }
  } else {
     $anything = $_SESSION['query_result'];
  }
while($data=mysqli_fetch_array($anything)){
   print_r($data);
}

标签:php,mysqli,session-variables
来源: https://codeday.me/bug/20191014/1911579.html