views:

50

answers:

1

Hi all,

Is there a way to cache results of a mysql query manually to a txt file?

Ex:

$a=1;
$b=9;
$c=0;
$cache_filename = 'cached_results/'.md5("$a,$b,$c").'.txt';
if(!file_exists($cache_filename)){
    $result = mysql_query("SELECT * FROM abc,def WHERE a=$a AND b=$b AND c=$c");
    while($row = mysql_fetch_array($result)){
        echo $row['name'];
    }
    // Write results on $row to the txt file for re-use
}else{
    // Load results just like $row = mysql_fetch_array($result); from the txt file
}

The original query contains more WHEREs and joins that uses multiple tables. So, Is this possible? If so, please explain.

Thank you, pnm123

+2  A: 

If you're sure that your data has a long time-to-live, you can certainly cache data by saving it temporarily to a text file.

if (!file_exists($cachefile)) {
    // Save to cache
    $query=mysql_query('SELECT * FROM ...');
    while ($row=mysql_fetch_array($query))
        $result[]=$row;
    file_put_contents($cachefile,serialize($result),LOCK_EX);
}
else
    // Retrieve from cache
    $result=unserialize(file_get_contents($cachefile));
foreach ($result as $row)
    echo $row['name'];

Although using APC, MemCache, or XCache would be a better alternative if you consider performance.

stillstanding
What if there are two or more rows/results? What do I need to use instead while($row=mysql_feth_array($result)){ ?
pnm123
then instead of `serialize($row)`, use `serialize($result)`
stillstanding
Sorry. I still didn't get the way of retrieving from cache. By the way, I've edited the question. So, how can I print multiple results by retrieving data from cache? just like while(){ echo; }
pnm123
Check my edited and more explicit answer.
stillstanding