getting list of users in Drupal 7 using PHP

21,367

Solution 1

Lets give it a try

$query = db_select('users', 'u');
    $query->fields('u', array('name'));
    $result = $query->execute();
    while($record = $result->fetchAssoc()) {
         print_r($record['name']);
    }

Solution 2

In Drupal 7 you can fetch all the users using entity_load,

To get the user names alone use the following,

$users = entity_load('user');
$user_names = array();
foreach ($users as $user_id => $user) {
  $user_names[] = $user->name;
}

Solution 3

user_load_multiple
Example from modules\profile\profile.pages.inc :

$users = user_load_multiple($uids);

$content = '';
foreach ($users as $account) {
  $profile = _profile_update_user_fields($fields, $account);
  $content .= theme('profile_listing', array('account' => $account, 'fields' => $profile));
}

Note that in drupal 7 all things happen via entity. It's not so fast, but flexible...

Solution 4

$query = db_select('users', 'u');

$query
  ->condition('u.uid', 0, '<>')
  ->fields('u', array('name'));

$result = $query->execute();

Here's the whole documentation for Drupal 7 Database api

Solution 5

Drupal 7 introduces a new concept of Entity. User also included in Entity now. You can use following function entity_load() to get the details of all entities.

To fetch the usernames in array :

$users = entity_load('user');
$usernames = array();
foreach($users as $id => $user){
    $usernames[$user->uid] = $user->name;
}
print_r($usernames);

Thanks

Share:
21,367
Bilal
Author by

Bilal

Experienced Full Stack Web Developer adept in all stages of advanced web development. Knowledgeable in user interface, testing, and debugging processes. Bringing forth expertise in design, installation, testing and maintenance of web systems. Equipped with a diverse and promising skill-set. Proficient in an assortment of technologies, including PHP, Python, Angular, NodeJS SQL, NoSQL and AWS. Able to effectively self-manage during independent projects, as well as collaborate in a team setting. I believe in high quality work, spend time to learn and implement something new and use everything in a better and modern way. I am very strong at fast learning, research and development and starting up fast on an ongoing project.

Updated on September 26, 2020

Comments