5

What is the preferred way of programmatically generating a list of users with a certain role?

(I know how to do it with a database query, but surely there's a higher-level method.)

4

In Drupal 7, user_load_multiple($uids = array(), $conditions = array(), $reset = FALSE) will load the user details for the given user IDs. In Drupal 6, there isn't that function, but you can use $user = user_load(array('uid' => $node->uid));.

  • Looping that line would mean I'd have to iterate through every user in the database (which doesn't scale well) — I'm looking for an efficient, programmatic way to generate a list of only users with a certain role. – smokris Dec 12 '11 at 14:28
  • if you are looking for efficient, nothing beats a well crafted db_query, so I guess I don't understand your hesitation at using one. after all, that's what any routine, drupal provided or otherwise, has to do anyway. – Jimajamma Dec 12 '11 at 14:33
3
SELECT u.* FROM users u,role r, users_roles ur WHERE r.name="authenticated user" AND r.rid=ur.rid AND ur.uid=u.uid;

try this query.

  • Thanks, but as I mentioned in my question, I know how to do it with a database query, and am wondering if there is a higher-level method. – smokris Dec 12 '11 at 14:26
1

Umm? Create a view of type USER, filter on USER ROLE, and have field USER NAME?

  • Thanks, but I'd like to do this programmatically (entirely from code). I know I can create a View from code, but that seems unnecessarily roundabout/heavyweight for a simple task like this. – smokris Dec 12 '11 at 6:02
  • This is not exactly how to do it programmatically. – kiamlaluno Dec 12 '11 at 10:46
  • what is this 'higher-level method' he speaks of? something between writing his own query and using the one views creates? – Jimajamma Dec 12 '11 at 14:27
  • @jimajamma: Yes, somewhere between those. For example, if I wish to fetch an object with user data, I call the function user_load() --- I don't have to directly query the database, nor do I have to build and execute a View --- resulting in code that's easier to maintain. – smokris Dec 12 '11 at 17:58
  • @jimajamma: How would I get a total count of these users per role? – cybercampbell Jun 20 '12 at 0:55

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.