Hello, I have the following code to add users to a particular role. The code works fine but I'd like to change the SQL so it only inserts the user into a role if it doesn't already exist.
Any help is greatly appreciated. Here is my code:
// ------------------------------------------------------------------
// ADD SELECTED USERS TO SELECTED ROLE
// ------------------------------------------------------------------
if(isset($_POST['ddlAddSelected']) && $_POST['ddlAddSelected'] != 'Add To' && isset($_POST['checked']))
{
// get checked checkbox values - userId
$checked = array_map('intval',$_POST['checked']);
// get selected security role - role name
$selected_role = mysqli_real_escape_string($conn, $_POST['ddlAddSelected']);
// get role id from db
$get_role_id = mysqli_query($conn, "SELECT RoleId, RoleName FROM roles WHERE RoleName = '$selected_role' Limit 1")
or die($dataaccess_error);
// if roleId present
if(mysqli_num_rows($get_role_id) == 1)
{
$row = mysqli_fetch_array($get_role_id);
$role_id = $row['RoleId'];
$role_name = $row['RoleName'];
$i=1;
foreach($checked as $user_id)
{
// add selected users to role
$add_selected = mysqli_query($conn, "INSERT INTO users_in_roles(UserId, RoleId, RoleName) VALUES($user_id, $role_id, '$role_name')")
or die($dataaccess_error);
$count = $i++;
}
// if sucess
if($add_selected)
{
$msg = "<div class='msgBox3'>SUCCESS: ($count) USERS have been ADDED to ($selected_role) ROLE.</div>";
}
else
{
echo 'some error message here...';
}
}
}
elseif(isset($_POST['ddlAddSelected']) && $_POST['ddlAddSelected'] != 'Add To' && !isset($_POST['checked']))
{
$msg = $msg_error;
}