Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the Drupal api to get a list of users?

Tags:

php

drupal

I would like to get a list of all the users who have been assigned a certain role. I could write my own SQL but I would like to use the api as much as possible.

like image 780
Lawrence Barsanti Avatar asked Jul 25 '09 21:07

Lawrence Barsanti


3 Answers

You can use entity_load to get array of users. Here is the sample that will create list of all emails for admin users (used to send notification)

<?php
$users = entity_load('user');
$emails = '';
foreach($users as $user) {
  if (array_key_exists(3, $user->roles)) {
    if (strlen($emails) > 0) {
      $emails .= ' ' . $user->mail;
    } else {
      $emails = $user->mail;
    }
  }
}
?>
like image 79
Dmitry Trifonov Avatar answered Oct 21 '22 05:10

Dmitry Trifonov


There are generally no Drupal API functions for this sort of task (pulling up entities that match certain criteria). It tends to focus on single-entity CRUD functions in the API; everything else is up to a developer's own SQL skills.

The Views module allows you to build lists of users filtered by role, permission, etc -- but it could easily be overkill.

like image 20
Eaton Avatar answered Oct 21 '22 05:10

Eaton


The SQL that worked for me:

$users = "";
$result = db_query('SELECT users.name AS users_name FROM users users
      INNER JOIN users_roles users_roles ON users.uid = users_roles.uid
      WHERE users_roles.rid = 4');

while ($existing_user = db_fetch_object($result)) {
      if ($users != "") $users .= ", ";
      $users .= $existing_user->users_name; // or do whatever
}
echo $users;

Keep in mind this is for Drupal 6 and I'm not sure about the performance of this for large user bases. Not sure about Drupal 7.

like image 27
joshmiller Avatar answered Oct 21 '22 03:10

joshmiller