Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch returns only one row when i get it from cache

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.

So I'm stuck and need your help.

like image 556
LetsSeo Avatar asked Sep 26 '22 20:09

LetsSeo


1 Answers

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>";
like image 156
Max P. Avatar answered Oct 03 '22 20:10

Max P.