Home > php教程 > php手册 > body text

PHP获取生成一个页面的数据库查询次数

WBOY
Release: 2016-06-13 09:39:17
Original
986 people have browsed it

很多博客软件都有这么一个功能,比如“生成本次页面一共花费了xx毫秒,进行了xx次数据库查询”等等。那么这个功能是如何实现的呢,下面我大概说下思路。

1. 在类的构造函数中声明全局变量

定义一个全局变量 $queries 用来统计页面生成经过的数据库查询次数。

function __construct()
{
	parent::__construct();
	global $queries;
}
Copy after login

2. 修改数据库类中封装好的的 query()

你应该有用到数据库类吧,找到它封装 query() 的方法,比如下面的:

// 执行SQL语句
public function query($query)
{
	//echo $query.'<br />';
	++$GLOBALS['queries'];
	return $this->result = mysql_query($query, $this->link);
}
Copy after login

那么每执行一次 Query,全局变量 queries 就会自增1。

3. 在方法体中这样写:

public function content($id = 0)
{
	$GLOBALS['queries'] = 0;
	// something to do
	echo $GLOBALS['queries'];
}
Copy after login

就这么简单就能实现那个功能了。

4. 附带计算PHP脚本执行的函数

之前写的博文介绍了下计算PHP脚本执行时间的函数,这里再贴一下吧。

// 计时函数 
public function runtime($mode = 0) { 
	static $t; 
	if(!$mode) { 
		$t = microtime(); 
		return; 
	} 
	$t1 = microtime(); 
	//list($m0,$s0) = split(" ",$t);
	list($m0,$s0) = explode(" ",$t);
	//list($m1,$s1) = split(" ",$t1);
	list($m1,$s1) = explode(" ",$t1);
	return sprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000); 
} 
Copy after login

使用如下:

public function content($id = 0)
{
	$this -> runtime();
	$GLOBALS['queries'] = 0;
	// something to do
	echo $GLOBALS['queries'];
	echo $this -> runtime(1);
}
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!