Last updated June 7, 2014. Created on September 3, 2010.
Edited by acabouet, silverwing, scarer. Log in to edit this page.

I needed to display a form for a user of a certain role to add and delete users of a certain role. Hopefully this code can help someone else.

<?php
/* only display if user role is web owner */
$rid = '';
global $user;
$cur_uid = $user->uid;
$result_user = db_query("SELECT u.uid, ur.rid FROM {users} u JOIN {users_roles} ur ON u.uid = ur.uid WHERE u.uid = $cur_uid AND ur.rid = '3'");
while ($row_user = db_fetch_object($result_user))
{
   $rid = $row_user->rid;
}
if ($rid != '')
{
   displayform();
}
else
{
   drupal_set_message('You do not have permission to access this content', 'warning');
}

function displayform()
{
/* Database queries */
$wausers = array();
$result = db_query("SELECT u.uid, u.name from {users} u JOIN {users_roles} ur ON u.uid = ur.uid WHERE ur.rid = '4' ORDER BY u.name ASC");
while($row = db_fetch_object($result))
{
   $wausers[$row->uid] = $row->name;
}
$allusers = array();
$result_two = db_query("SELECT u.uid, u.name from {users} u ORDER BY u.name ASC");
while($row_two = db_fetch_object($result_two))
{
   $allusers[$row_two->uid] = $row_two->name;
}

/* Checking form submissions */
foreach($wausers as $key => $value)
{
   if($_POST[$key])
   {
       //remove user from webauthor role
       db_query("DELETE FROM {users_roles} WHERE uid = '$key' AND rid = '4'");
       drupal_set_message($value . ' has been removed from web author role.');
   }
}
if ($_POST['webauthor'])

   foreach($allusers as $key => $value)
   {
      if ($_POST['webauthor'] == $key)
      {
         //add user to webauthor role
         db_query("INSERT INTO {users_roles} (uid, rid) VALUES ('$key', '4')");
         drupal_set_message($value . ' has been added to web author role.');
      }
   }
}

/* HTML Output */
/* only print if form has not been submitted */
if(!$_POST)
{
foreach($wausers as $key => $value)
{
   $output.= '<tr><td><a href="user/' . $key . '">' . $value . '</a></td><td><input type="checkbox" name="' . $key .'" value="uid"></td></tr>';
}
echo '<h2>Remove Users</h2><form name="removewebauthors" action="" method="POST"><table><th>Name
</th><th>Delete</th>' . $output . '</table><input type="submit" value="delete"></form>';
$output_two .= '<option value="">-select user-</option>';
foreach($allusers as $key => $value)
{
      $output_two.= '<option value="' . $key . '">' . $value . '</option>';
}
echo '<br><h2>Add Users</h2><form name="addwebauthors" action="" method="POST">
<select name="webauthor">' . $output_two . '</select><br><br><input type="submit"
value="submit"></form>';
}
}
?>

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.