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

Let*_*Seo 5 php mysql pdo caching phpfastcache

我正在尝试采用缓存类在我的网页上使用.

简单的逻辑是这样的:

尝试从缓存中获取数据:

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

我的代码

<?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>";
}

?>
Run Code Online (Sandbox Code Playgroud)

我的输出和问题

我有两排.

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

row1
row2
Run Code Online (Sandbox Code Playgroud)

但是当页面从缓存中将它带给我时,它只输出最后一行.

row2
Run Code Online (Sandbox Code Playgroud)

我试过的

我尝试使用fetchAll()函数而不是fetch()但这次我收到通知:未定义的索引:id错误.

所以我被困住了,需要你的帮助.

Max*_* P. 4

如果一次处理所有记录,请使用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>";
Run Code Online (Sandbox Code Playgroud)