Mrs-Anders
Mrs-Anders

Reputation: 1

Get user uid from name (Drupal 7)

I can't figure out how to get an user's UID knowing the user's name.

The user's name will be entered by a variable. I just need to pick up the UID in another variable.

I've found this code, which would be perfect, but it doesn't work on Drupal 7:

$account = user_load(array('name' => check_plain($name)));

Can anybody help me? Thank you very much!!

Upvotes: 0

Views: 1221

Answers (2)

Vinod Kumar
Vinod Kumar

Reputation: 352

try

$user = user_load_by_name($username);
$user_id = $user->uid;

or you can use

function get_uid($username)
{    
    // Function that returns the uid based on the username given
    $user = db_fetch_object(db_query("SELECT uid FROM users WHERE name=':username'", array(":username" => $username)));

    return $user->uid;
}

Upvotes: 2

Triss
Triss

Reputation: 96

One way to look up the user is to use the entity_load('user');. Here is an example how to do it:

// Add the user you want to find here
$user_to_lookup = 'test';

$users = entity_load('user');


$found_user = null;
foreach ($users as $user) {
    if ($user->name == $user_to_lookup ) {
        $found_user = $user;
    }
}

The user object is stored in $found_user now. Note that its an stdClass so you need to use the arrow notation to access the properties. For example to access mail write $found_user->mail.

Upvotes: 0

Related Questions