When troubleshooting queries built with Drupal 7’s Database API (affectionately known as “DBTNG”), there often comes a time when I need to see the actual query that’s going to be executed in the database. Here’s a quick and handy tip to assist query troubleshooting.
The Devel module has a function called dpq (“devel print query”) that receives a query and prints out the string version, with arguments escaped and everything.
Suppose you have a query with arguments, like the following:
$query = db_select('node', 'n')
->fields('n')
->condition('n.type', 'page');
You can very easily see the contents of this query by using dbq:
dpq($query);
Essentially, it uses the the query object’s __toString method to get the stringified version of the query, and additionally injects the escaped arguments into the query.
Very handy!