Count the number of MySQL Queries
How to count the number of MySQL queries used by your script
One way of optimizing your scripts that connect to MySQL databases is to determine how many queries to the database your script makes. If you would like to count the number of queries, you can write a script that will do so. You use this function in place of the regular mysql_query() function.
PHP Code:
<?php function cnt_mysql_query($sql=FALSE) { static $queries = 0; if (!$sql) return $queries; $queries ++; return mysql_query($sql); } $sql= "SELECT 8+9"; cnt_mysql_query($sql); $result = cnt_mysql_query('SELECT 4*12'); cnt_mysql_query('SELECT 78+5'); echo '<br />Database Queries: ' . cnt_mysql_query(); ?>
From the PHP manual:
A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope [exits the function].
Consider the following example:
PHP Code:
<?php function Test () { $a = 0; echo $a; $a++; } ?>
This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
PHP Code:
<?php function Test() { static $a = 0; echo $a; $a++; } ?>
Now, every time the Test() function is called it will print the value of $a and increment it."
Note: A static variable is static for the life/duration of a browser page. If the page is refreshed the static variable will revert back to the initial value each time the page is refreshed.