How to print SQL query with arguments in drupal 7 | Debugging SQL Query

August 08, 2014
1K
12K


Category:
Tags:

Drupal Provide us nice API function to print the query which is built using db_select() in a programmatical way

If you have not Devel Module installed

<?php$query = db_select('node', 'n'); $query-&gt;join('users', 'u', 'n.uid = u.uid'); //JOIN node with users $query-&gt;groupBy('u.uid');//GROUP BY user ID $query-&gt;fields('n',array('title','created'))//SELECT the fields from node -&gt;fields('u',array('name'))//SELECT the fields from user -&gt;orderBy('created', 'DESC')//ORDER BY created -&gt;range(0,2);//LIMIT to 2 records // Print Query as string print $query-&gt;__toString(); // or // Second way // echo (string)$query; // print arguments in query echo '?>

<?php';print_r($query-&gt;arguments()); echo '?>

<?php'; ?&gt; ?>

If you have Devel Module installed

You can use dpq() to display the query, and dpr() to display the result.

<?php$query = db_select('users','u'); $query-&gt;fields('u'); $query-&gt;condition('u.uid', 1042); $result = $query-&gt;execute()-&gt;fetchAll(); dpq($query); // Display the query. dpr($result); // Display the query result. ?>