This example shows how to generate a list of nodes using the Drupal framework. The code assumes you have already loaded Drupal (see Bootstrap if you want to place this code in an external script.)

1. Query the database for node ids
2. Load the full nodes based on their ids
3. Generate html output

Step 1: Query the database

The function db_query_range() executes a general query with a set limit (see the reference page for more information.)

In this instance we are searching for the latest 15 blog entries

$total_entries = 15; //max results
$result = db_query_range(db_rewrite_sql('SELECT * FROM {node} n
WHERE n.status = 1 AND n.type = "blog"
ORDER BY n.changed DESC'), 0, $total_entries);

At this point the $result variable will have a data reference to our result set. To get all that data we’ll use db_fetch_array() to return each row as an array. If you prefer to get the row as an object, use db_fetch_object() instead.

You could read and process each line with a while() statement:

while ($data = db_fetch_array($result)) {
//perform operations such as loading the node and generating html

I personally like to grab the entire set to manipulate at my leisure, so I’ll place everything into the $data variable as an array:

while ($data[] = db_fetch_array($result)) {} //put everything into $data var
array_pop($data); //remove the last array element as it will be empty

STEP 2: Load the nodes

At this point, the $data variable has a list with the last 15 blog nodes, but this list only includes basic information such as the title, ids and the date of last change. In order to use this data, we’ll need to use the ids we have to load the full node.

$nodeid = $data[0][‘nid’]; //grab an id to use
$mynode = node_load($nodeid); //load a node object into $mynode

Step 3: Generate HTML for the node

The next step is to generate HTML based on the node. There are a few functions that can help here. For instance, if I want to keep it simple and let Drupal generate the entire chunk of code for my node:

$summary = true;  //summary view or full node view
print node_view($mynode, $summary);

If I want to render my own title code, and just want the node summary:

print $data[0][‘title’]; //the node title as extracted from the database
$summary = true; //summary view or full node view
print node_build_content($mynode, $summary); //print only the summary, not the title and other elements

All together, my code to generate the list from the $data array:

foreach ($data as $key=>$value) {
print node_view(node_load($value['nid']), true);

Additional references:
- Drupal database abstraction layer
- Node-related functions