views:

22

answers:

1

In a drupal block, you can access the node variables by using node_load(arg(1)). But how do you get the comment variables in a block?

A: 

If you need to get the list of all the comments made for a node, you can use the following code:

$query = 'SELECT c.nid, c.subject, c.cid, c.timestamp FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE c.nid = %d AND n.status = 1 AND c.status = %d ORDER BY c.cid DESC';

$result = db_query(arg(1), COMMENT_PUBLISHED);
while ($comment = db_fetch_object($result)) {
  $comments[] = $comment;
}

Rather then just using arg(1), which would not consider the node revision in URLs like /node/<nid>/revision/<rid>, you should use menu_get_object(); in that case the code would become:

$node = menu_get_object();
if (!empty($node) && !empty($node->nid)) {
  $query = 'SELECT c.nid, c.subject, c.cid, c.timestamp FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE c.nid = %d AND n.status = 1 AND c.status = %d ORDER BY c.cid DESC';
  $result = db_query($query, $node->nid, COMMENT_PUBLISHED);
  while ($comment = db_fetch_object($result)) {
    $comments[] = $comment;
  }
}
kiamlaluno
In the case you are interested only to `$number` comments, use `db_query_range($query, $node->nid, COMMENT_PUBLISHED, 0, $number)`.
kiamlaluno
I've put a region in the comment area and assigned a block to it, and I want to access $comment->cid.
Toxid