Search code examples
phpdrupal-7rolesuser-roles

How to get a list of users in a certain role?


I'm creating a module in Drupal 7 that needs to get a list of users from a certain role. I've seen examples showing how to get the logged in user's role, and a list of roles, but I haven't seen anything to help me get the list of users in a certain role. Is there a way to do this? I was trying to use user_role, but that only gave me a list of the roles that existed. Is there something else I should be doing with it?


Solution

  • user_roles() is actually implemented in such a way that it searches the roles database table to extract all roles. You could do similar thing and search the users table for a given role. Please look at the function below

    function getUsersByRole($rid = 1) { // rid = Role Id from users_roles table
        $query = db_select('users', 'u');
        $query->fields('u', array('uid', 'name'));
        $query->innerJoin('users_roles', 'r', 'r.uid = u.uid');
        $query->condition('r.rid', $rid);
        $query->orderBy('u.name');
    
        $result = $query->execute();
    
        $users = array();
        foreach ($result as $user) {
            $users[] = $user;
        }
    
        return $users;
    }
    
    $users = getUsersByRole(3);
    var_dump($users);
    

    Make sure you will run it within Drupal environment.