Drupal: Get a Username from a User ID

I've been really enjoying working with Drupal - the more I learn about it, the more ideas I get on how to use it. Yet, sometimes it can make a simple thing a bit daunting - like fetching a user's name from a user id, without needed to load the entire user object with user_load() - which can get expensive.

So, here's a handy little function. Just plop it in your template.php file for your theme of choice, and it will be available where you need it on your site (as long as you're using that template!):

// DON'T DO IT THIS WAY - READ ON
//function getUserName($id) {
//  $sql = "SELECT name FROM {users} WHERE uid = '$id'";
//  $result = db_query(db_rewrite_sql($sql));
//  $username = db_fetch_object($result);
//  return $username->name;
//}
 
// After learning more Drupal, this is the better way:
// note that $id must be a number
 
function getUserName($id) {
  return db_result(db_query("SELECT name FROM {users} WHERE uid = %d", $id));
}

To use it for output, just do something like:

<?php print getUserName(1234); ?>

Using This With the Views Module

I often use this with the Views module. For example, I have a View for displaying all content created by a given user. The URL looks something like this:

http://www.some-drupal-site.com/user/1234/recent

The "1234" is the user id argument getting passed to the view. The view will then go in and fetch content created by this user id. Oftentimes I want to create a nice header in the View with dynamic output - but Views doesn't really allow that sort of thing in the header/footer areas under Basic Settings. So I use this function to get around it. In the view's header, I do this to fetch a username:

<?php
  $view=views_get_current_view();
  $user_name = getUserName($view->args[0]);
  print '<h1>Content created by  ' . $user_name . '</h1>';
?>

*Note that to get the PHP input type working, you need to allow the PHP Filter in the modules section, and then select PHP as the input type for this view's header.

Note that after you click the Update button, the Views module may give you an error message - that's OK. It just doesn't know what to do with this php code outside of the actual page you're going to use it on.Below is a screenshot example.

user-header-views.png

Hope this helps someone! And if you know a better way to do this, speak up! Cheers.

This entry was posted in Drupal. Bookmark the permalink.

12 Responses to "Drupal: Get a Username from a User ID"

Leave a reply