Cache results of a mysql query manually to a txt f

2019-04-12 23:15发布

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

1条回答
姐就是有狂的资本
2楼-- · 2019-04-12 23:21

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.

查看更多
登录 后发表回答