手动将mysql查询的结果缓存到txt文件 [英] Cache results of a mysql query manually to a txt file

查看:75
本文介绍了手动将mysql查询的结果缓存到txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以将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

解决方案

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

>

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是​​更好的选择.

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.

这篇关于手动将mysql查询的结果缓存到txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆