What's the best way to perform a custom database query in Drupal and then work with the results? For example:

I want to hard-code a custom query into the page.tpl.php file that basically grabs all of the titles from the database and let's me manipulate them as I want. Logically, I would think it could look something like this:

$queries = drupal_database_query("SELECT * FROM node");
foreach ($queries as $query) {
echo $query->title . "
";
}

...something like that. Basically I'm asking if Drupal has a built-in function to make custom queries?

Comments

DriesK’s picture

http://api.drupal.org is where you can find all information you need. More specifically at http://api.drupal.org/api/5/group/database for the db abstraction layer. Make sure to read the initial guidelines.

So you could do something like:

$result = db_query('SELECT * FROM {node}');
while ($node = db_fetch_object($result)) {
  print $node->title;
}
Scourge’s picture

If you just want a means of testing a PHP DB query, you can paste it into a new page with the PHP input filter enabled. Or use something like the devel module to test just the SQL query alone as a starting point.