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()) {

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

Example from modules\profile\ :

$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');

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

$result = $query->execute();

Here's the whole documentation for Drupal 7 Database api

Solution 5

Your code was almost correct if you had changed your while statement to read

while ($result as $row) 

db_fetch_object is no longer needed in d7

it would have worked. Although db_select calls specified in this post will work, they require more overhead and should be avoided unless you are trying to generate dynamic queries. Also see: for info on how the apis have chaned between d6 and d7. A search for db_fetch_object on this page would've given this info.

Author by


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 June 04, 2022


  • Bilal
    Bilal 16 days

    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)) {