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

| Published Date: 26 Aug 2014 | Last Updated Date: 04 Sep 2017
Total Reads: 3,616 | Last Visit: 21 Sep 2017 07:02:10 PM

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

  1. $query = db_select('node', 'n');
  2. $query->join('users', 'u', 'n.uid = u.uid'); //JOIN node with users
  3. $query->groupBy('u.uid');//GROUP BY user ID
  4. $query->fields('n',array('title','created'))//SELECT the fields from node
  5. ->fields('u',array('name'))//SELECT the fields from user
  6. ->orderBy('created', 'DESC')//ORDER BY created
  7. ->range(0,2);//LIMIT to 2 records
  9. // Print Query as string
  10. print $query->__toString();
  12. // or
  13. // Second way
  14. // echo (string)$query;
  16. // print arguments in query
  17. echo '<pre>';print_r($query->arguments()); echo '</pre>';
  18. ?>

If you have Devel Module installed

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

  1. $query = db_select('users','u');
  2. $query->fields('u');
  3. $query->condition('u.uid', 1042);
  4. $result = $query->execute()->fetchAll();
  6. dpq($query); // Display the query.
  7. dpr($result); // Display the query result.



Post new comment

The content of this field is kept private and will not be shown publicly.
Max length 128 characters
Enter the characters shown in the image.

About This Mania

Hasan Hafiz, Blogger at web mania ltd (www.webemania.com). He has more than 5 years experience in web development platform. He worked as a Sr. Software Developer at Canadian based outsourcing software firm, Lead Developer at countries top most VOIPswitch development company and Sr. Software Engineer at USA based outsourcing software firm . His expertise areas are PHP, MySQL, CSS, Javascript, JQuery, HTML, XML and MVC Framework Codeigniter. He has been along with Drupal from more than 4 years. You may call him Drupal Addicted.