Drupal: returns SQL string from db_query

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

Or else, take the returned resource identifier from db_query and get the SQL string?


Edit:

In addition, I recently learned about db_queryd()from the Devel module, which echoes the transmitted request (and also executes it). It does not return a string as this question asked, but is very useful for copying and pasting a full query.

+3
source share
7 answers

I do not think so. However, if you do this for debugging purposes only, you can enable the devel module and show that requests are being executed.

'dev_query' 1, $, .

+3

Drupal 7, debug, \include\database\database.inc:

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

$stmt queryString

print_r($stmt->getQueryString());
+2

D7, Devel , — , ... , ( ).

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

Drupal, , , Drupal, .

+2

devel. , , , , db_query(). , , , , .

+1

,

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

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

, .

, db_query, sprintf , .

+1
source

For those using Drupal 7.x and Devel , the correct call function to output the built-in SQL statement to the drupal message area is dpq (). However, you need to pass the request object. eg.

// to see the built SQL
$query = db_select('node', 'n')->fields('n');    
dpq($query);

// to see the results of the query
$results = $query->execute()->fetchAssoc();
dsm($results);

Hope this helps!

0
source

D7 version with devel.

> = PHP 5.4

dpm(str_replace(['{', '}'], '', dpq($query, TRUE)));

<PHP 5.4

dpm(str_replace(array('{', '}'), '', dpq($query, TRUE)));
0
source

Source: https://habr.com/ru/post/1752192/


All Articles