2015-12-23 13 views
5

Sto provando ad adottare una classe cache da utilizzare sulla mia pagina web.fetch restituisce solo una riga quando ottengo dalla cache

logica semplice è così:

Cercate di ottenere i dati dalla cache:

  • Se non c'è: query correre e impostare questo come una cache.
  • Se c'è: mostra i dati dalla cache.

mio codice

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

?> 

la mia uscita e di problem

Ho due righe.

Quando li prelevo dalla query, il mio codice li emette entrambi. Che è bello

row1 
row2 

Ma quando pagina lo porta a me dalla cache, emettere solo nell'ultima riga.

row2 

quello che ho cercato

Ho cercato di usare fetchAll() funzione invece di fetch() ma questa volta sto ottenendo Avviso: Errore ID: Undefined index.

Quindi sono bloccato e ho bisogno del tuo aiuto.

+0

Vuoi avere cache per ogni record o cache per tutti i record? –

+0

Aggiorna la tua domanda con il metodo 'get' e' set' della classe 'Cache'? –

+0

@MaxP. Voglio mettere in cache tutti i record contemporaneamente. – LetsSeo

risposta

4

se per tutti i record in una sola volta, utilizzare 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>";