我有下面显示的以下代码,以允许管理员通过从可用角色(复选框)中进行选择来将特定用户添加到多个角色。该代码可以很好地完成此操作,但它还需要删除未选中角色(复选框)的用户。复选框允许管理员从所选角色中添加和删除用户。这是我无法弄清楚的部分。
如果有人能引导我完成这一切,那将是非常棒的。谢谢!
<?php
// declare variables
$msg = '';
// ------------------------------------------------------------------
// UPDATE USER INFO
// ------------------------------------------------------------------
if(isset($_POST['UpdateUser']))
{
// get user id from query string sent
$sent_id = mysqli_real_escape_string($conn, $_GET['uid']);
if(isset($sent_id) && !empty($sent_id) && is_numeric($sent_id) && $sent_id > 0)
{
$user_id = $sent_id;
// ------------------------------------------------------------------
// ADD CURRENT USER TO SELECTED ROLES
// ------------------------------------------------------------------
if(isset($_POST['checked']))
{
// get selected role names
$checked = $_POST['checked'];
$i1=0;
$i2=0;
foreach($checked as $role_name)
{
// get role id
$get_role_id = mysqli_query($conn, "SELECT RoleId FROM roles WHERE RoleName = '$role_name'")
or die($dataaccess_error.mysqli_error($conn));
$row = mysqli_fetch_array($get_role_id);
$role_id = $row['RoleId'];
// check if user already exist in role
$check_if_exist = mysqli_query($conn, "SELECT UserId, RoleId, RoleName FROM users_in_roles WHERE UserId = $user_id AND RoleId = $role_id AND RoleName = '$role_name' LIMIT 1")
or die($dataaccess_error);
if(mysqli_num_rows($check_if_exist) == 0)
{
// add user to roles
$add_user_to_roles = mysqli_query($conn, "INSERT INTO users_in_roles(UserId, RoleId, RoleName) VALUES($user_id, $role_id, '$role_name')")
or die($dataaccess_error.mysqli_error($conn));
$count1 = $i1++ + 1;
$count2 = $i2;
$msg = "<div class='msgBox3'>SUCCESS: USER have been ADDED to ($count1) ROLES - AND ALREADY EXISTS in ($count2).</div>";
}
elseif(mysqli_num_rows($check_if_exist) == 1)
{
$count1 = $i1;
$count2 = $i2++ +1;
$msg = "<div class='msgBox4'>NOTE: USER have been ADDED to ($count1) ROLES - AND ALREADY EXISTS in ($count2).</div>";
}
}
}
else
{
$msg = $msg_error2;
}
}
}
?>