程序
最后,我们来定制一个应用,综合的来解释 PEAR 缓冲机制的整体框架。
我们定义一个叫做 MySQL_Query_Cache 的类,缓冲 SELECT 的查询结果。
我们首先定义类的变量:
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 result)) {
return $this->result[$this->cursor++];
} else {
return false;
}
}
function num_rows() {
return sizeof($this->result);
}
?>
下面我们来看怎样缓冲:
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 查询缓冲
$cache = new MySQL_Query_Cache();
$cache->connect(’hostname’, ’username’, ’password’, ’database’);
$cache->query(’select * from table’);
while ($row = $cache->fetch_row()) {
echo ’
’;
print_r($row);
echo ’
}
?>

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版
SublimeText3 Linux最新版

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能