我如何存储/序列化php返回的mysqli_query结果?

问题描述

我正试图将MysqLi_query返回的结果存储为缓存,因此,如果执行相同的“ SELECT”语句,它将从缓存中获取而不是通过MysqL服务器,但是无论我尝试什么,以下代码序列化/ json_encode,解码甚至只是将输出存储为变量,我做不到

        $row = $this->result->fetch_object();

代码如下。有人知道为什么吗?我如何只存储返回的结果并重新使用它?它不适用于$ this-> result = MysqLi_query($ dbh,$ query);

                global $dbcache;
//                      $this->result = MysqLi_query( $dbh,$query );
                if (isset($dbcache[$query])){
                        $this->result = json_decode($dbcache[$query]);
//                        echo 'JSON? = '.$query.'<br>'.$dbcache[$query];
                }else{
//                      echo ' === '.$dbcache[$query].' === '."\n";
                        $this->result = MysqLi_query( $dbh,$query );
                        //$dbcache[$query] = serialize($this->result);
                        $dbcache[$query] = json_encode($this->result);
//                      echo 'Serialize? = '.$query."\n".hash('sha3-512',$query).'<br>';
                }

解决方法

存储<h1 id="date_heading">Date</h1> <input id="date_input" type="date"> <button id="button">Submit</button>对象的时间不应超过获取数据所需的时间。它仅用作临时对象,用于从MySQL提取数据。而是缓存值。

mysqli_result

但是,我会警惕这种方法对预准备语句的有用性。您可能希望将键组合为查询和参数。例如:

if (isset($dbcache[$query])) {
    $this->result = $dbcache[$query];
} else {
    $dbcache[$query] = $this->result = $dbh->query($query)->fetch_all(MYSQLI_ASSOC);
}

您确实应该从在应用程序代码中使用mysqli函数抽象出来。如果要构建某种抽象层,则只能将数据返回给应用程序,并且只能在内部使用mysqli。使用我推荐的方法,您将以常规数组的形式访问数据。没有更多的$key = serialize([$query,...$params]); if (isset($dbcache[$key])) { $this->result = $dbcache[$key]; } else { //prepare bind execute $stmt = $dbh->prepare($query); if ($params) { $stmt->bind_param(str_repeat("s",count($params)),...$params); } $stmt->execute(); // Fetch results into multidimensional array $dbcache[$key] = $this->result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); } 方法。当然,这需要您更改应用程序代码,但这是一个好主意。我也强烈建议您开始使用PDO。