Is there any core function to get uid from username in Drupal? Or I should perform a db query? my field is a textfield with '#autocomplete_path' equal to 'user/autocomplete'
You can use the user_load
function. See http://api.drupal.org/api/function/user_load/6
In particular see http://api.drupal.org/api/function/user_load/6#comment-6439
So you would do something like this:
// $name is the user name
$account = user_load(array('name' => check_plain($name)));
// uid is now available as $account->uid
node_load
, which is similar in concept to user_load
happens a lot in Drupal, if I'm not wrong, and yet doesn't adversely affect performance in most cases. So I thought it would be a good idea to recommend user_load
–
Alina user_load()
does not use static caching like node_load()
does, so if that call is going to be made often during a page cycle, it might be better to do a custom query. –
Whipstitch Somehow I couldn't make the query work but I found this:
$user = user_load_by_name($username);
$user_id = $user->uid;
see: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load_by_name/7
The user load function is very heavy, would use up more resources and return more data than required, Here is a nice little function for you:
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;
}
Note: This code is revised and input is escaped, so the code is not dangerous in any way.
You can get all the info about logged user with global $user
variable.
The code is:
<?php
global $user;
$uid = $user->uid;
echo $uid;
?>
There is no ready made API function for this, not that I know of. But you can make your own if you needs several places. It should be pretty simple and straight forward to query the db for the uid.
© 2022 - 2024 — McMap. All rights reserved.