0

I have a dilemma i just can't figure out, and i need your help. The thing is, I wish to display the ip address of the logged in user in my custom form. The problem i have is how do i make it based on the logged in user?

The following is the code i used:

$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1', array(':uid' =>33));

echo "Hostname:" . $hostname . "
";

2 Answers 2

2

If you want the logged in user info, try the following (I have not tested, but it should work).

global $user;

$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1', array(':uid' =>$user->uid))->fetchField();

The global $user object will return information from the currently logged in user. You might want to put some authentication in to check that the user is logged in if this is used in an area where anonymous users can visit. Maybe wrap it in an if statement like I've done below:

if (user_is_logged_in() == TRUE) {

  global $user;

  $hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1", array(':uid' => $user->uid))->fetchField();

  echo 'Hostname: ' . $hostname;
}
else {
  echo 'You are not logged in.';
}
0
0

The logged in user is available in the global $user variable:

global $user;
$uid = $user->uid;

$args = array(':uid' => $uid);
$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1", $args)->fetchField();

Note the use of fetchField() above...it's a handy utility method to grab a single field result from a compatible query. Since you're requesting a single row and a single field you might as well use this method for brevity.

1
  • Thanks Clive, i love the idea of separating my arguments, so i dont have to repeat my variables. Awesome! :) ps: it worked like a charm too.
    – vaeros
    Commented Jan 31, 2012 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.