2

I want to load a node with its images in Drupal 7, such as using the following code:

  $current_node = node_load(arg(1));
  db_query("SELECT nid, title FROM {node} WHERE type = :type AND created < :created LIMIT 1", array(':type' =>  $current_node->type, ':created' => $current_node->created))->fetchObject()

I wish to load the image field in the content; I think I should use left join to load the image file.

Does anybody know what to do next? What is the image table name?

1

You're going to have to join another table for every field that you want to grab the data for, which is just a pain. Instead, you could just get the nid with your query, and use node_load() a second time to get the other node object, complete with attached fields.

You can do that like so:

$args = array(':type' => $current_node->type, ':created' => $current_node->created);
$sql = 'SELECT nid FROM {node} WHERE type = :type AND created < :created';
$nid = db_query_range($sql, 0, 1, $args)->fetchField();

$new_node = node_load($nid);

$title = $node->title;
$image_field_values = field_get_items('node', $new_node, 'field_image');

$first_image = array_shift($image_field_values);
$image_file = file_load($first_image['fid']);

$image_html = theme('image_style', array(
  'style_name' => 'thumbnail',
  'path' => $image_file->uri,
  'alt' => 'Some alt text'
));

$body_values = field_get_items('node', $new_node, 'body');

// And so on
2
  • because I need to theme the image by using theme('image_style', array('style_name' => 'thumbnail', 'path' => url); so I need to know the path of the image, how can I extract the image url from the variable $image_field_values?
    – helxsz
    May 26 '12 at 21:17
  • I've put an example in the answer, hope it helps
    – Clive
    May 26 '12 at 21:51
1

Yes and to add more to it, if you use node load it is safer because then the Drupal caching will by default will work for you. And if you are writing queries to get the result then every time the page is going to get a hit, the query will be fired and no caching will be done by default. You have to explicitly handle the caching at this point of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.