Mar
11

PHP数据查询缓存的实现(三)

此方案适合以相对时间收久的缓存,对于相对更新比较快,但也需要缓存提速的可以选择memcache
脚本:

$file = 'sql_cache.txt';

$expire = 86400; // 24 小时

if (file_exists($file) &&

filemtime($file) > (time() - $expire)) {

$records = unserialize(file_get_contents($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);

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

共计 0 条评论

NAME:

required

E-MAIL:

required, will not be published

HOMEPAGE:

CONTENT: