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

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

// 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>";