Getting the Nodes Content

Armed with the Node ID, we can retrieve a specific piece of content from the database.

To do this, we could write another (more complex) SQL statement to get the node contents. Since node content is spread across multiple tables, we would have to make use of a couple of joins to get the desired content. Fortunately, there is a simpler way.

The Drupal node API provides a convenient function that does the heavy lifting for us: node_load(). If we pass this function the NID, it will return an object that contains the node's contents.

[ _ " Nodes are implemented using a Drupal module. The main node API I

(found in drupal/modules/node/node.module) provides dozens of I methods for working with nodes. I

Using node_load(), we can finish off our function as follows:

function _philquotes_get_quote() { $sql = "SELECT nid FROM {node} ".

"WHERE status=1 AND type='quote' ORDER BY RAND() LIMIT 1"; $res = db_query($sql); $item = db_fetch_object($res); $quote = node_load($item->nid); return $quote;

Only the highlighted lines are new. All we are doing here is fetching the complete node object with node_load(), and then returning this object. (If node_load() is given a NULL value, it simply returns FALSE. We are relying on the philquotes_block() function to deal with empty results.)

What does this do in the context of our module? Let's look back at the lines of philquotes_block() that we worked on earlier:

$item = _philquotes_get_quote(); if(!empty($item)) {

$content = theme('philquotes_quote', check_plain($item->body), check_plain($item->title));

The $item variable in philquotes_block() now contains the node object we just retrieved with _philquotes_get_quote() (the value of $quote). We have the data we need. Now we need to format it for display.

Next, we will look at the theme() function (and some related code), and how it handles turning our object into a themed string.

Was this article helpful?

0 0

Post a comment