Drupal: Return SQL string from db_query

13,138

Solution 1

I don't think it is. However if you are only doing so for the purpose of debugging you can turn on the devel module and that will show you the queries run.

Actually you could just set the variable 'dev_query' to 1 and then access the global array $queries, but I wouldn't recommend it.

Solution 2

Drupal 7, if debug, you could find at \includes\database\database.inc:

function query($query, array $args = array(), $options = array())

$stmt's queryString

or

print_r($stmt->getQueryString());

Solution 3

If you have D7 but don't have Devel to hand, the following snippet could come in useful — it may not handle every type of placeholder however... it currently wrongly assumes all placeholders are strings (which has been fine for my usage).

function stringify_query( $query ){
  $s = preg_replace('/\}|\{/', '', $query->__toString());
  $a = $query->arguments();
  foreach ( $a as $key => $val ) {
    $a[$key] = '\'' . $val . '\'';
  }
  return strtr($s, $a);
}

It also rudely strips out Drupal's curly braces used to handle table prefixes, if you rely on table prefixes then you should find the correct Drupal function to have them replaced correctly.

Solution 4

I would recommend the use of the devel module. There is a setting devel offers which will show all queries run during the generation of a page at the bottom of the page, with data on query execution time and the function that called db_query(). If you have a general idea of what your query will look like or the function that called it, you could search for it within your browser and you can see what was actually send to the database.

Solution 5

Late answer, but you can often turn

$result = db_query($query, $arg1, $arg2);

quickly into

drupal_set_message(sprintf($query, $arg1, $arg2), "status");

And get what you want.

This doesn't help you if you are using an array as your argument to db_query as sprintf doesn't support that, but is often useful in your debugging toolkit.

Share:
13,138
ack
Author by

ack

Updated on June 04, 2022

Comments

  • ack
    ack almost 2 years

    Is it possible to return the actual SQL query as a string from the result of db_query?

    Or otherwise take the returned resource ID from db_query and get the SQL string?


    Edit:

    As an addendum, I recently found out about db_queryd() from the Devel module, which echoes the query passed (as well as execute it). Doesn't return the string as this question asked, but really helpful for copying and pasting a complete query.