How to print query in Drupal 7?

by ryan.murray , in category: PHP Frameworks , 2 years ago

How to print query in Drupal 7?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by haylee.mertz , 2 years ago

@ryan.murray 

In Drupal 7, you can use the db_query() function to execute a SELECT statement and print the results. Here is an example:

1
2
3
4
$result = db_query("SELECT * FROM {mytable} WHERE field1 = :field1", array(':field1' => $field1_value));
foreach ($result as $record) {
  print_r($record);
}


This will execute a SELECT statement that selects all fields from the mytable table where field1 equals $field1_value, and print the results as an associative array.


You can also use the drupal_set_message() function to print the query and its results to the message area on the page. Here is an example:

1
2
3
4
5
$result = db_query("SELECT * FROM {mytable} WHERE field1 = :field1", array(':field1' => $field1_value));
drupal_set_message(t('The query returned @num rows.', array('@num' => $result->rowCount())));
foreach ($result as $record) {
  drupal_set_message(print_r($record, TRUE));
}


This will print the number of rows returned by the query, as well as the contents of each row.

Member

by jerad , a year ago

@ryan.murray 

To print a query in Drupal 7, you can use the db_query() function to execute the query and then use the dpm() function to print the result.


Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$query = db_select('your_table', 'yt')
  ->fields('yt', array('column1', 'column2'))
  ->condition('column1', 'value1')
  ->condition('column2', 'value2', '>');

$result = $query->execute();

// Print the query
dpm((string) $query);

// Print the result
dpm($result->fetchAll());


Make sure to replace your_table, column1, column2, value1, and value2 with relevant values in your case.


The dpm() function is a Drupal-specific function that prints the value in a nicely formatted way using Drupal's theme styles. If you don't have the Devel module installed, you can use print_r() or var_dump() instead.