store mysqli_query result in session

2019-02-28 18:27发布

问题:

I want to store the result of a MySQLi query as a session variable so that I can reuse it without executing the query again. I don't want to execute the same query on every page of my website or every time a page is refreshed.

I've tried the code below, but I get errors like "object can not be stored in session" and "mysqli_fetch_array expects parameter one to be a resource".

How can I store the query result in a session?

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 */
}

回答1:

Try this:

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


回答2:

If you want to store the data not only for one client, but serverside I would recommend you to look at how to build a in-memory server side cache in php?. Some frameworks have this already built in.

Otherwise use one of the mysqli API methods like http://php.net/manual/de/mysqli-result.fetch-assoc.php, this should return you an array not an object.

mysqli_query() returns an object which you can not store into session (there is a method for converting an object to an array, but I would not recommend you to store the whole object) http://php.net/manual/de/function.get-object-vars.php



回答3:

Use like this:

$result = $connection->query("select something from table");
$_SESSION['session-name'] = $result->fetch_assoc();

OR

$sql = `select something from table`;
$result = mysqli_query($sql);
$_SESSION['session name'] = mysqli_fetch_assoc($result);