Drupal 7 Code Snippets for Blocks Pages

Sharing some of the code snippets related to Drupal 7. As you know that in Drupal 7 the API has changed and the SQL snippets that you used in Drupal 6 will no longer work in drupal 7. This was a big problem for me. This article will be useful if you dont know much coding, but can manage minor changes to code.

Display Top X Node Authors (exclude user=1)


<?php
    $limit = 5;
    $query = db_select('node', 'n');
    $query->join('users', 'u', 'n.uid = u.uid');
    $query->fields('u',array('name'));
    $query->condition('u.status', 1);
    $query->condition('n.status', 1);
    $query->condition('u.uid', '1','!=');  // This will exclude user 1
    $query->addExpression('COUNT(n.uid)');
    $query->groupBy('u.uid');
    $query->orderBy('COUNT(n.uid)', 'DESC');
    $query->range(0, $limit);
    $result = $query->execute();
    $output = "<ul>";
    while($record = $result->fetchAssoc()) {
        $output .= "<li>" . $record['name'] . "(" . $record['expression'] . ")" . "</li>";
    }
    $output .= "</ul>";
    echo $output;
?>


Display total number of users

 
<?php
     // Count query for users without rid 3
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->where('u.uid NOT IN(select uid from {users_roles} where rid = :rid)', array(':rid' => 3));  
  $count= $query->countQuery()->execute()->fetchField();
  $count1 = "Total number of users: ";  
  $count1 .=  $count;  
  echo $count1;
  ?>