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

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

аз 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
In reply to dave c

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

аз Tim Hunt -
Сурати  корбар Core developers Сурати  корбар Documentation writers Сурати  корбар Particularly helpful Moodlers Сурати  корбар Peer reviewers Сурати  корбар 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.
In reply to Tim Hunt

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

аз 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..