将mysql查询的结果手动缓存到txt文件

时间:2010-09-11 18:43:12

标签: php mysql caching

有没有办法将mysql查询的结果手动缓存到txt文件?

例如:

$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
}

原始查询包含更多使用多个表的WHERE和联接。 那么,这可能吗?如果是,请解释。

谢谢你, pnm123

1 个答案:

答案 0 :(得分:3)

如果您确定您的数据有很长的生存时间,您当然可以通过将数据临时保存到文本文件来缓存数据。

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'];

虽然如果考虑性能,使用APC,MemCache或XCache会是更好的选择。