Php 当我从缓存中获取它时,fetch只返回一行
我正在尝试采用一个缓存类来在我的网页上使用 简单的逻辑如下: 尝试从缓存中获取数据:Php 当我从缓存中获取它时,fetch只返回一行,php,mysql,caching,pdo,phpfastcache,Php,Mysql,Caching,Pdo,Phpfastcache,我正在尝试采用一个缓存类来在我的网页上使用 简单的逻辑如下: 尝试从缓存中获取数据: 如果没有:运行查询并将其设置为缓存 如果有:显示缓存中的数据 我的代码 <?php // Require Library require_once("phpfastcache.php"); $cache = phpFastCache(); //lets get it from cache. $r = $cache->get("cachethis"); if($r == null) {
- 如果没有:运行查询并将其设置为缓存
- 如果有:显示缓存中的数据
<?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>";
}
?>
但当页面从缓存中将其带给我时,它只输出最后一行
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>";
$r=$cache->get(“cachethis”);
如果(!is_数组($r)){
//不在缓存中,来自数据库
$query=$handler->query(“从成员中选择*);
$r=$query->fetchAll(PDO::FETCH_ASSOC);
$cache->set(“cachethis”,$r,10);
}
foreach($r as$v)echo$v['id']。“
”;
您想对每个记录进行缓存还是对所有记录进行缓存?请使用get
和set
方法cache
class?@MaxP更新您的问题。我想一次缓存所有记录。
$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>";