hi,

i need the mysql query for identifying the current logged user.is any one knows plz share with me.

thanks

Comments

nicksanta’s picture

No query required. To get the current user's object, use the following snippet.

<?php
global $user;
?>

That simple :)

vasan.85’s picture

hi

Actually i need to display the current user friends in map.regarding to that i need mysql query to get the current logged user id.how i do that.will you help to that

thanks

nevets’s picture

User id (uid) is part of $user, example

<?php
global $user;
print
$user->uid;
?>
dlsso’s picture

Here is a "hack" I wrote that does that and also creates a variable with the access level of the user:

$con = mysql_connect("localhost","root","");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_select_db("drupal", $con);

$sid = session_id();
$userline = mysql_query("SELECT uid FROM sessions WHERE sid='$sid'");
$u_row = mysql_fetch_row($userline);
$uid = $u_row[0];

if ($uid == 0){$accesslvl = 99;}
else{
$accessline = mysql_query("SELECT rid FROM users_roles WHERE uid=$uid");
$a_row = mysql_fetch_row($accessline);
$accesslvl = $a_row[0];
}

If you just want to get the user ID your code would look like this:

//Connect to the database. Drupal probably does this for you, but I don't remember. Including it just in case.
$con = mysql_connect("yourhost","youruser","yourpassword");
if (!$con){die('Could not connect: ' . mysql_error());}
//Select database
mysql_select_db("yourdatabase", $con);

//Define a variable as the session ID
$sid = session_id();
//Define a variable as the user ID by selecting the uid column of the row in the "sessions" table that matches the session ID we got earlier
$userline = mysql_query("SELECT uid FROM sessions WHERE sid='$sid'");
//Even though it's only one item the mysql query returns values as arrays so we need to use fetch_row or fetch_array to pull out the value we want
$u_row = mysql_fetch_row($userline);
$uid = $u_row[0];

//Now you have a variable ($uid) that is equal to the user id for that session. If you want you can print it
echo $uid;

//Or use it to get other info. Example:

//This sets access level to 99 for anyone who's not logged in, and then
//grabs the role ID (rid) from the row containing the user ID in the user_roles table
//And sets that as the access level ($accesslvl)
if ($uid == 0){$accesslvl = 99;}
else{
$accessline = mysql_query("SELECT rid FROM users_roles WHERE uid=$uid");
$a_row = mysql_fetch_row($accessline);
$accesslvl = $a_row[0];
}

Note:
There might be typos in the commented part. The original code block is clear for sure though.

nevets’s picture

The code should be using the db abstraction layer, db_query() and db_fetch_array() in this case. The code should not directly connect to the Drupal database, core handles that.

You can also do that more directly using the global $user object.

dlsso’s picture

Yah, I'm a noob and I wrote that for a non-drupal page, hence the manual connect.