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:
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.
So I'm stuck and need your help.
if for all records at once, use 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>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With