2

I am trying to add a record in a table based upon the UID of a member in my Drupal site. I am doing this with a form that is on each member's page. For this to work properly, I need to use the UID in the mysql query. This is being included in the page with a in a Drupal block.

If I use $uid = $user->uid;, it will be my UID as admin. I need for it to populate with the UID of of the member whose page I am currently viewing.

Here's a little snippet of my code:

mysql_query("INSERT INTO profile_values (fid, uid, value) VALUES ('99','$uid', '$newcompany')");

I need to define $uid and this will work perfectly! (this is Drupal Commons, if that makes a difference)

Clive
  • 36,918
  • 8
  • 87
  • 113
nitsuj
  • 780
  • 1
  • 11
  • 27

1 Answers1

2

If you're on a user page then whatever the current URL is the underlying router path will be user/%, where % is the user's ID.

With this in mind you can use Drupal's arg() function to grab the parts of the URL split by the / character, and thus the user ID:

// This if statement just checks that you're on a user page.
if (arg(0) == 'user' && is_numeric(arg(1)) {
  $uid = arg(1);
}

Bear in mind the if above will also match paths such as user/%/edit so if that's going to cause a problem just add && is_null(arg(2)) to the conditions.

Clive
  • 36,918
  • 8
  • 87
  • 113
  • Thanks for your reply! I haven't tried your example yet, but I thought of something similar that worked (although it may not be the best way to do it?). I did this: `//get user id from url $url = $_SERVER['REQUEST_URI']; $array = explode("/",$url); $uid = $array[3];` because the url is tld/directory-of-drupal-site/user/uid/edit – nitsuj Jan 10 '12 at 19:55
  • 1
    It's probably safer to use the `arg()` function in case you enable URL aliases later on...it would stop working with that code. Otherwise though that's pretty much exactly what the `arg()` function does, but using `$_GET['q']` instead of `$_SERVER['REQUEST_URI']` :) – Clive Jan 10 '12 at 20:14