帝国软件
  设为首页 加入收藏 关于我们
 
解密帝国网站管理系统
栏 目:
 
您的位置:首页 > 技术文档 > PHP编程
采用 PEAR 来缓冲 PHP 程序(二)
作者: 发布时间:2005-03-11 来源:justDN

最后,我们来定制一个应用,综合的来解释 PEAR 缓冲机制的整体框架。


我们定义一个叫做 MySQL_Query_Cache 的类,缓冲 SELECT 的查询结果。

我们首先定义类的变量:

<?php
require_once 'Cache.php';

class MySQL_Query_Cache extends Cache {
var $connection = null;
var $expires = 3600;

var $cursor = 0;
var $result = array();

function MySQL_Query_Cache($container = 'file',
$container_options = array('cache_dir'=> '.',
'filename_prefix' => 'cache_'), $expires = 3600)
{
$this->Cache($container, $container_options);
$this->expires = $expires;
}

function _MySQL_Query_Cache() {
if (is_resource($this->connection)) {
mysql_close($this->connection);
}

$this->_Cache();
}
}
?>



在正式开始之前,我们需要一些辅助函数。

function connect($hostname, $username, $password, $database) {
$this->connection = mysql_connect($hostname, $username, $password) or trigger_error('数据库连接失败!', E_USER_ERROR);

mysql_select_db($database, $this->connection) or trigger_error('数据库选择失败!', E_USER_ERROR);
}

function fetch_row() {
if ($this->cursor < sizeof($this->result)) {
return $this->result[$this->cursor++];
} else {
return false;
}
}

function num_rows() {
return sizeof($this->result);
}
?>



下面我们来看怎样缓冲:

<?php
function query($query) {
if (stristr($query, 'SELECT')) {
// 计算查询的缓冲标记
$cache_id = md5($query);

// 查询缓冲
$this->result = $this->get($cache_id, 'mysql_query_cache');

if ($this->result == NULL) {
// 缓冲丢失
$this->cursor = 0;
$this->result = array();

if (is_resource($this->connection)) {
// 尽可能采用 mysql_unbuffered_query()

if (function_exists('mysql_unbuffered_query')) {$result = mysql_unbuffered_query($query, $this->connection);
} else {$result = mysql_query($query, $this->connection);
}

// 取出所有查询结果
while ($row = mysql_fetch_assoc($result)) {$this->result[] = $row;
}

// 释放 MySQL 结果资源
mysql_free_result($result);
// 把结果缓冲
$this->save($cache_id, $this->result, $this->expires, 'mysql_query_cache');
}
}
} else {
// 没有查询结果,不需要缓冲
return mysql_query($query, $this->connection);
}
}
?>



例 3: 使用 MySQL 查询缓冲

<?php require_once 'MySQL_Query_Cache.php';

$cache = new MySQL_Query_Cache();
$cache->connect('hostname', 'username', 'password', 'database');
$cache->query('select * from table');

while ($row = $cache->fetch_row()) {
echo '<p>';
print_r($row);
echo '</p>';
}
?>

<全文完>

  
评论】【加入收藏夹】【 】【打印】【关闭
※ 相关链接
无相关信息

   栏目导行
  PHP编程
  ASP编程
  ASP.NET编程
  JAVA编程
   站点最新
·致合作伙伴的欢迎信
·媒体报道
·帝国软件合作伙伴计划协议
·DiscuzX2.5会员整合通行证发布
·帝国CMS 7.0版本功能建议收集
·帝国网站管理系统2012年授权购买说
·PHPWind8.7会员整合通行证发布
·[官方插件]帝国CMS-访问统计插件
·[官方插件]帝国CMS-sitemap插件
·[官方插件]帝国CMS内容页评论AJAX分
   类别最新
·Windows下集成安装Apache,PHP,MYSQ
·Mysql注入:SQL Injection with MyS
·PHP 的来龙去脉
·PHP 的功能概述
·PHP与其它CGI的比较
·PHP 的编译配置详细选项
·php.ini 配置详细选项
·如何写作PHP程序
·Hello,World
·嵌入方法
 
关于帝国 | 广告服务 | 联系我们 | 程序开发 | 网站地图 | 留言板 帝国网站管理系统