background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Querying the Drupal database and fetching all the results in an associative array

Eric.London's picture

Here's a code snippet to show how to execute a query and fetch all the results into an associative array:

<?php
// create the SQL in a string
$sql = "
  select *
  from {node} n
  where n.status = '1'"
;

// execute the query
$resource = db_query($sql);

// loop through the resource and fetch the rows
$results = array();
while (
$row = db_fetch_array($resource)) $results[] = $row;

// show the results
echo "<pre>" . print_r($results, TRUE) . "</pre>";
?>

You have

You have saved my life once again!!

You are a genius!

sql

Hi,

Just learning Drupal, but one thing I noticed, you are embedding/hardcoding variables into your SQL. Is this safe? I thought part of the point of db_query() was to encourage use of "tokens" in the query (for security reasons)?For example, I think we are encouraged to simply do this:

$resource = db_query("select * from {node} n where n.status = '1' and n.uid = %d", db_escape_string($GLOBALS['user']->uid);

Eric.London's picture

tokens

Yes, thanks for mentioning that. Using tokens will help validate the data types of your SQL arguments. You should never make assumptions about the validity of your input and output variables.

More information about the db_query function here:
http://api.drupal.org/api/function/db_query/6

The purpose of my original post was to show how to execute a query and create an associative array of the results. You're right though, there is no excuse for my sloppy SQL example, which I would not use in the real world.

Sanitizing SQL

In regard to that last comment: If you know that the module your creating is solely for display purposes and not at all dependent on user input then wouldn't keeping the SQL simplified be more optimal for speed?