What's most efficient way to get the username from an id?

What's most efficient way to get the username from an id?

by dave c -
Number of replies: 4
I have a userid (it was handed to me from an external system).

I've been using:

$user = get_complete_user_data('id', $userId);
if (!$user) {
// no user found,
return false;
}
return $user->username;

to see if the id is valid. It seems like there is probably a better way, one that doesn't tax the database so much.

Any suggestions?
-Dave
Average of ratings: -
In reply to dave c

Re: What's most efficient way to get the username from an id?

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
If you really only want the username, do

return get_field('user', 'username', 'id', $userid);

If, however, you want to do more with the user later, it is better to get the whole $user record in one shot:

return get_record('user', 'id', $userid);

although that changes the API.
Average of ratings: Useful (1)
In reply to Tim Hunt

Re: What's most efficient way to get the username from an id?

by dave c -
Perfect. Thanks.
In reply to Tim Hunt

Re: What's most efficient way to get the username from an id?

by Siddharth Patel -

Greetings,

I m trying the same, but due to I am working on moodle 2.2.3 so it is giving me an error get_field() not available anymore.

Can you please say if there is any other solution?

Regards..