开发者

Cache results of a mysql query manually to a txt file

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜