WEB开发网
开发学院WEB开发PHP php+mysql缓存技术 阅读

php+mysql缓存技术

 2012-08-22 11:32:41 来源:WEB开发网   
核心提示:// file_get_contents() 适合于for PHP < 4.3.0$file = 'sql_cache.txt';$records = unserialize(implode('',file($file)));//现在你可以通过$records数组并且取得原始查询的


// file_get_contents() 适合于for PHP < 4.3.0
$file = 'sql_cache.txt';
$records = unserialize(implode('',file($file)));
//现在你可以通过$records数组并且取得原始查询的数据:
foreach ($records as $id=>$row) {
print $row['category_name']."<br>";
}
/* 注意$records是数组(一个包含了查询结果的数字索引列——每行是一个数字和一个字符串...真是混乱)的一排。
把它们放在一块:
基于本例子中的时间来决定是否缓存。如果文件修改的时间戳比当前时间戳减去过期时间戳大,那么就用缓存,否则更新缓存。
<!--[if !supportLists]-->l <!--[endif]-->检查文件是否存在并且时间戳小于设置的过期时间
<!--[if !supportLists]-->l <!--[endif]-->获取存储在缓存文件中的记录或者更新缓存文件
$file = 'sql_cache.txt';*/
$expire = 86400; // 24 小时 (单位:秒)
if (file_exists($file)&&filemtime($file) > (time() - $expire)){
// 取得缓存中的记录
$records = unserialize(file_get_contents($file));
} else {
// 通过 serialize() 函数创建缓存
}
/*附加其它可能的:
<!--[if !supportLists]-->l <!--[endif]-->把缓存结果存储在共享内存中以获取更快的速度
<!--[if !supportLists]-->l <!--[endif]-->增加一个功能随机地运行SQL查询并且检查是否输出与缓存输出一致。如果不一致,则更新缓存(本函数运行次数的概率可以定为1/100)。通过哈希算法(如MD5())可以协助判断字符串或者文件是否改变。
<!--[if !supportLists]-->l <!--[endif]-->增加一个管理员的功能,人工的删除这个缓存文件,以强制更新缓存(如file_exists()函数返回false时)。你可以用函数unlink()删除文件。
脚本:*/


$file = 'sql_cache.txt';
$expire = 86400; // 24 小时
if (file_exists($file)&&filemtime($file) > (time() - $expire)) {
$records = unserialize(file_get_contents($file));
//$records=unserialize(fread($file,filesize($file)));
} else {
$link = mysql_connect('localhost','username','password') or die (mysql_error());
mysql_select_db('shop') or die (mysql_error());
/* 构造SQL查询 */
$query = "SELECT * FROM categories";
$result = mysql_query($query) or die (mysql_error());
while ($record = mysql_fetch_array($result) ) {
$records[] = $record;
}
$OUTPUT = serialize($records);
$fp = fopen($file,"w");
//fputs($fp, $OUTPUT);
fwrite($fp,$OUTPUT);
fclose($fp);
} // end else


// 查询结果在数组 $records 中
foreach ($records as $id=>$row) {
if ($row['category_id'] == $_REQUEST['category_id']) {
// 被选择的目录显示粗体字
print '<B>'.$row['category_name'].'</B><BR>';
} else {
// 其它目录显示用常规字体
print $row['category_name'].'<br>';
}
} // end foreach

上一页  1 2 3 

Tags:php mysql 缓存

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接