Hi,
in this script, I will show you how to count the number of mysql queries exectuted and to get the execution time of the mysql queries in php.
First, we have to count the number of times that mysql_query is used, so we will make a function that count the number of times she is executed and that same function will get the execution time of the queries.
This is the code:
<?php
//connexion
mysql_connect($host,$username,$password);
mysql_select_db('mydatabase');
//We start the counter at 0
$nb_queries = 0;
//The function to time the execution time
function timer()
{
$time = explode(' ', microtime());
return $time[0]+$time[1];
}
$timer_queries = 0;
//The fonction that count the number of queries and their execution time
function query($query)
{
//We increase the queries counter by 1
global $nb_queries,$timer_queries;
$nb_queries++;
//Execute the query and time the execution time
$beginning = timer();
//Execute the query and save the result in a variable
$req_return = mysql_query($query);
//We add the query duration to the total
$timer_queries += round(timer()-$beginning,6);
return $req_return;
}
//We run some queries for the example
$requete1 = query('select count(username) as nb from users');
$donnee1 = mysql_fetch_array($requete1);
echo "The Data Base contain ".$donnee1['nb']." users.<br />";
$requete1 = query('select username from users');
echo "This is a list of the users:<br />";
while($donnee1 = mysql_fetch_array($requete1))
{
echo "<strong>".$donnee1['username']."</strong><br />";
}
//Show the result
echo $nb_queries.' mysql queries executed in '.$timer_queries.' seconds';
?>
Test
I hope this script will be useful.
Similar Scripts and Tutorials