getting list of users in Drupal 7 using PHP
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
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, 2020Comments
-
Bilal about 3 years
How can I fetch user names from a Drupal 7 database using PHP?
See this: Is it possible to use the Drupal api to get a list of users?
This is for Drupal 6 and I have tried this but it says
Call to undefined function db_fetch_object()
Here is my code:
$result = db_query("SELECT name AS users_name FROM {users}"); while($row = db_fetch_object($result)) { print_r($row); }
-
q9f over 9 years-1 dont use database queries if there is a drupal function for that. stackoverflow.com/a/6766138/1260906 or stackoverflow.com/a/17282755/1260906 or drupal.stackexchange.com/a/46437/13526
-
I.P about 9 yearsActually this function creates an issue, it changes current user session. Loads another user session automatically.