How to print query in Drupal 8?

by aniya.jaskolski , in category: PHP Frameworks , 2 years ago

How to print query in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@aniya.jaskolski you can cast to string or use toString() method to print raw SQL query in Drupal 8, code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

$connection = \Drupal::service('database');
$query = $connection->select('node', 'node');
$query->fields('node', ['nid']);
$query->condition('node.type', 'article');

// Print query
print_r($query->__toString());
// Print query params
print_r($query->arguments());


by haylee.mertz , a year ago

@aniya.jaskolski 

To print a query in Drupal 8, you can use the dsm() function. Follow these steps:

  1. Make sure the Devel module is installed and enabled. You can install it using composer with the command composer require drupal/devel.
  2. Enable the Devel module by going to Admin -> Extend and checking the box next to "Devel" module. Save the configuration.
  3. In your custom module or theme, add the following code to print the query:
1
2
3
4
5
6
7
$query = Drupal::database()->select('tablename', 't')
  ->fields('t', ['field1', 'field2', ...])
  ->condition('field_condition', $value)
  // add more conditions or other query operations if needed
  ->execute();

dsm($query->__toString());


Replace 'tablename' with the actual table name and 'field1', 'field2', ... with the desired field names. You can also add additional conditions or other query operations as required.

  1. Clear the Drupal cache by running drush cr or by going to Admin -> Configuration -> Development -> Performance and clicking on "Clear all caches" button.
  2. Visit the page where you want to print the query. You should see the query printed in a popup window or at the bottom of the page, depending on your Devel module configuration.


Note: The dsm() function can be used to print other variables as well, not just queries.