Drupal - How do I assign a new role to all the existing accounts on the site?
One option would be to do it via the GUI (admin/people) where you can select all the shown users with the uppermost checkbox and then under 'update options' add the role you want. If it's a one time thing for ~300 users then this is probably the quickest way to handle it.
For a programmatic approach the user_multiple_role_edit() function can be used. You need to pass the user id-s as an array, the operation and role id to the function and it'll do the rest for you. You can get the role id by checking the edit link of the wanted role via the GUI (admin/people/permissions/roles).
To get all the user id-s and assign them the role you could use the following example (modify where needed):
$result = db_query('SELECT uid FROM {users}');
$uids = array();
foreach ($result as $record) {
if ($record->uid == 0) continue;
$uids[] = $record->uid;
}
user_multiple_role_edit($uids, 'add_role', 4);
If you would like to do this programatically you should be able to do it using something like this:
// load user based on user id
$user = module_invoke('user', 'load', $uid);
// get array of roles for user
$roles = $user->roles[];
// assign a new role for the user
$roles[] = 'newrole';
// save the updated roles for the user
module_invoke('user', 'save', $user, array('roles' => $roles));
Of course the above just works for a single record, but you could use a db_query()
call to retrieve a list of all user ids.
The following link might come in handy: http://drupal.org/node/28379
If you want to go the module route, you can use Views Bulk Operations. Create a view (in Views) that lists all the users on your site and then add an "add a role" action with Views Bulk Operations; this will allow you to select all users on your site at once and apply the role.
VBO (Views Bulk Operations) can also be used to simplify many other administrative tasks. The module page links to a large number of tutorials so I won't link to any here.