How to display the query executed by the Drupal view How to display the query executed by the Drupal view php php

How to display the query executed by the Drupal view


Or you can use hook_views_pre_execute along with devel's dpq function:

function MY_MODULE_views_pre_execute(&$view) {  dpq($view->build_info['query']);}


Set the Footer's Input Format to PHP, and paste this snippet into the Footer text:

<pre><?php  $v = views_get_current_view();  $query = db_prefix_tables(vsprintf($v->build_info['query'], $v->build_info['query_args']));  $replacements = module_invoke_all('views_query_substitutions', $v);  $query = str_replace(array_keys($replacements), $replacements, $query);  echo $query;?></pre>

For a syntax-highlighted query (using geshifilter.module), use the following snippet:

<pre><?php  require_once drupal_get_path('module', 'geshifilter') .'/geshifilter.pages.inc';  $v = views_get_current_view();  $query = db_prefix_tables(vsprintf($v->build_info['query'], $v->build_info['query_args']));  $replacements = module_invoke_all('views_query_substitutions', $v);  $query = str_replace(array_keys($replacements), $replacements, $query);  echo geshifilter_process($query, 'sql');?></pre>

(Stemmed from @Owen's answer and discussion with @Mech-Software in the comments.)


The query exists in the view object. Depending on where you want to use it, you may want to add the variable in a views preprocess function, or the location you're calling the view (if calling it programatically).

If you're just using the default template for it though, you can have access to it there:

// ex. somewhere in your views-view--VIEW_NAME.tpl.php<?php print db_prefix_tables($view->build_info['query']); ?>

Be careful if your process takes arbitrary SQL though, may be better to call it with the view name, and have it programatically pick up results as required. Or, have a secondary display on your view which returns the result in a XLS result set directly.