Every serious Drupal developer has heard of the Devel module. This little devil can do a lot of things like being a firefug for Drupal theming, content generation, ... But one of it's most interesting features is the displaying of queries run during a page request. Excellent performance monitoring tool while debugging!
But did you know that the monitoring of queries is built right into Drupal? Devel just builds upon it.
You can activate this feature by setting the variable dev_query to 1. As there's no interface to do this, the quickest way is to set the $conf array in settings.php.
$conf['dev_query'] = 1;
When this variable is set to one, all queries issued via db_query and it's brothers and sisters like db_query_range, pager_query are gathered in a global variable $queries. Global variables can be accessed anywhere by declaring the variable as global (again).
function test() {
global $queries;
print_r($queries);
}
And there you have it! All queries are printed out using print_r.
The best moment to see which queries were run is of course at the end of the request. In Drupal this is possible using hook_exit. But other modules might still issue some queries there (like the statistics module). If we wanna catch those too, it's best to use a PHP core function: register_shutdown_function. Using this function you can register another function that should be run after all other code has been run. A good moment to register this function is during hook_init.
function my_module_init() {
register_shutdown_function('display_queries');
}
function display_queries() {
global $queries;
print '<pre>';
print_r($queries);
print '</pre>';
}


