当我从缓存中获取时,fetch只返回一行


fetch returns only one row when i get it from cache

我正在尝试采用一个缓存类来在我的网页上使用。

简单的逻辑是这样的:

尝试从缓存获取数据:

  • 若并没有:运行查询并将其设置为缓存
  • 如果有:显示缓存中的数据

我的代码

<?php
// Require Library
require_once("phpfastcache.php");
$cache = phpFastCache();
//lets get it from cache.
$r = $cache->get("cachethis");
if($r == null) {
    echo " THIS TIME RUN WITHOUT CACHE <br> ";
    $time_start = microtime(true);
    $query = $handler->query("SELECT * FROM members");
        while($r = $query->fetch(PDO::FETCH_ASSOC)) {
        //echo
        echo "$r[id]";
        //lets cache query above.
        $cache->set("cachethis", $r, 10);
        }
    $time_end = microtime(true);
    $time = ($time_end - $time_start);
    echo "<p>done in " . $time . " seconds</p>";
} 
//if ($r != null)
else {
    echo "RUN WITH CACHE. YES.<br>  ";
    $time_start = microtime(true);
    //echo from cache..
    echo "$r[id]";
    $time_end = microtime(true);
    $time = ($time_end - $time_start);
    echo "<p>cache done in " . $time . " seconds</p>";
}
?>

我的输出和问题

我有两排。

当我从查询中获取它们时,我的代码会同时输出它们。这很好。

row1
row2

但当页面把它从缓存中带到我这里时,它只输出最后一行。

row2

我尝试了什么

我尝试使用fetchAll()函数而不是fetch(),但这次我得到了注意:未定义的索引:id错误。

所以我陷入困境,需要你的帮助。

如果同时对所有记录使用fetchAll

$r = $cache->get("cachethis");
if(!is_array($r)) {
    // not in cache, from db
    $query = $handler->query("SELECT * FROM members");
    $r = $query->fetchAll(PDO::FETCH_ASSOC);
    $cache->set("cachethis", $r, 10);
}
foreach($r as $v) echo $v['id']."<br>";