Hi all,

I want to modify a user's role (preferably through the RID) using php-code on a page or as 'additional processing in a webform. I've been burrowing through many posts on the forum that _almost_ supply the answer to my 'challenge' but not quite. Installing Organic Groups, which is suggested to offer this functionality, is a bit of an overkill in my opinion (considering how many queries Drupal does already to load a page).

Trying a few options failed, using the 'official' way like user_save, module_invoke('user', 'save', ...) and a hook_user example. I ended up using the example below, which works. However, I feel that it's wrong to put a db_query into the page just like that!

So basically, my question is whether anyone feels like sharing their knowledge in making the below code 'safer' or at least moet universal. I'd like to use the available Drupal API/hooks/functions, but can't find a clear "this is how it works" description.

<?php
/** This script checks whether user is "group_a" or "group_b", both with specific limitations and if so, upgrades this user to "authenticated user" (RID=2).  Includes a check to prevent admin user from accidentally being downgraded.  **/

global $user;
$uid = $user->uid;
if (((in_array('group_a',$user->roles)) || (in_array('group_b',$user->roles))) && !($uid == '1')) {
  echo '<em>[User has been changed to \'authenticated user\']</em><br>';
  db_query("UPDATE users_roles SET users_roles.rid = '2' WHERE users_roles.uid = '%d'", $user->uid);
cache_clear_all('menu:'. $user->uid, TRUE);  //to clear the user-role cache and thus prevent the new role from being overwritten
}
else {
  echo '<em>[User has NOT been changed, was not in the target groups]</em><br>';
}
?>

I believe this code (in more proper form) can be used to many ends when dealing with user roles.

Thanks for practical pointers!

Harro