How to print query in Drupal 7?

by ryan.murray , in category: PHP Frameworks , 8 months ago

How to print query in Drupal 7?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , 3 months 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.