我如何存储/序列化 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>';

                }


翻阅古今
浏览 54回答 1
1回答

冉冉说

您存储对象的时间不应mysqli_result超过获取数据所需的时间。它仅用作从 MySQL 获取数据的临时对象。而是缓存值。if (isset($dbcache[$query])) {&nbsp; &nbsp; $this->result = $dbcache[$query];} else {&nbsp; &nbsp; $dbcache[$query] = $this->result = $dbh->query($query)->fetch_all(MYSQLI_ASSOC);}但是,我对这种方法对于准备好的语句的有用性持谨慎态度。您可能希望将键设为查询和参数的组合。例如:$key = serialize([$query, ...$params]);if (isset($dbcache[$key])) {&nbsp; &nbsp; $this->result = $dbcache[$key];} else {&nbsp; &nbsp; //prepare bind execute&nbsp; &nbsp; $stmt = $dbh->prepare($query);&nbsp; &nbsp; if ($params) {&nbsp; &nbsp; &nbsp; &nbsp; $stmt->bind_param(str_repeat("s", count($params)), ...$params);&nbsp; &nbsp; }&nbsp; &nbsp; $stmt->execute();&nbsp; &nbsp; // Fetch results into multidimensional array&nbsp; &nbsp; $dbcache[$key] = $this->result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);}您确实应该避免在应用程序代码中使用 mysqli 函数。如果您正在构建某种抽象层,那么您应该只将数据返回到应用程序并仅在内部使用 mysqli。使用我推荐的方法,您将像普通数组一样访问数据;没有更多的fetch_object()方法了。当然,这需要您更改应用程序代码,但这样做是个好主意。我还强烈建议开始使用 PDO。
打开App,查看更多内容
随时随地看视频慕课网APP