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

时间:2022-10-20 03:35:23

I'm trying to adopt a cache class to use on my web page.

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

Simple logic is like that:

简单的逻辑是这样的:

Try to get data from cache:

尝试从缓存中获取数据:

  • If there is not: run query and set this as a cache.
  • 如果没有:运行查询并将其设置为缓存。
  • If there is: show data from cache.
  • 如果有:显示来自缓存的数据。

my code

我的代码

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

?>

my output and problem

我的输出和问题

I have two rows.

我有两排。

When I fetch them from query, my code outputs both of them. Which is nice.

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

row1
row2

But when page brings it to me from cache, it outputs only last row.

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

row2

what i tried

我试过的

I tried to use fetchAll() function instead of fetch() but this time I'm getting Notice: Undefined index: id error.

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

So I'm stuck and need your help.

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

1 个解决方案

#1


4  

if for all records at once, use fetchAll

如果一次为所有记录,请使用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>";

#1


4  

if for all records at once, use fetchAll

如果一次为所有记录,请使用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>";