2009
11.27

After many hours of searching and not finding any examples for query profiling I liked, I decided to “bite the bullet” and write my own. This extends the default MySQLi class and adds the query profiling I was looking for with a very minimal amount of code. The joys of OOP. :)

<?php
//mysqlii.php

//Create class
class mysqlii extends mysqli
{
	//Create properties
	var $query_time;
	var $query_count;

	//Override default method
	function query($query)
	{
		//Start timer, run query, stop timer
		$query_begin = microtime(TRUE);
		$result = parent::query($query);
		$query_end = microtime(TRUE);

		//Die if query problem
		if($this->error):
			die('An error has occurred! Please try your request again shortly.');
		endif;

		//Set properties
		$this->query_time += $query_end - $query_begin;
		$this->query_count++;

		//Return query results
		return $result;
	}
}
?>

Usage example. This also includes page profiling.

<?php
//Start timer
$page_begin = microtime(TRUE);

//Include new class
include('mysqlii.php');

//Open connection to database
$db = @new mysqlii('host', 'username', 'password', 'database');

//Die if connection error
if($db->connect_error):
	die('Unable to connect to the database!');
endif;

//Build and run query
$query = "SELECT * FROM test";
$db->query($query);

//Continue your code

//Close connection to database
$db->close();

//Stop timer and set variable
$page_end = microtime(TRUE);
$page_time = $page_end - $page_begin;

printf('Page generation: %fs', $page_time); //Page generation: 0.257650s
printf('DB queries: %u (%fs)', $query_count, $query_time) //DB queries: 1 (0.002195s)
?>

No Comment.

Add Your Comment