如果未选中 select 选项,则将其从数据库中删除 - Bootstrap Multiselect

If select option is unchecked, delete it from Database - Bootstrap Multiselect

我有一个 html table,其中一列带有 bootstrap- 多选。我希望数据库在未选中复选框时删除角色。

我正在使用 if (isset($_POST['roles_checkbox'])) 收听更改。因此,当复选框未被选中时,它永远不会被调用并且什么也不会发生。如果用户有 2 个角色并且 1 个未选中,则它会被删除。然而,如果用户有 1 个角色,则无法将其删除。我希望用户能够没有分配给他们的角色。

<?php
echo "
  <!--User Roles-->
  <td>
  <form method='post'>
    <input type='hidden' name='user_id' value=" . $row["user_id"] . ">"; ?>
    <select class='roles_checkbox' multiple='multiple' name="roles_checkbox[]" 
    onchange='this.form.submit()'>

      <?php $a = 1; ?>
      <?php foreach ($roles as $data):
        $new_sql = "SELECT role_id from users_roles, users WHERE users_roles.user_id = '" . 
        $row["user_id"] . "' AND users_roles.role_id = '" . $a . "' GROUP BY 
        users_roles.user_id";
        $checked_or_not = mysqli_query($connect, $new_sql);?>
          <option value="<?php echo $a ?>" <?php if ($checked_or_not->num_rows != 0) echo 
          "selected=\"selected\""; ?>><?php echo $data ?></option>
        <?php $a++; ?>
     <?php endforeach; ?>
   </select>

<?php
  echo "
  </form>
  </td>";

<!--Update User Role listenning to select box-->
if (isset($_POST['roles_checkbox'])) { // Use select name
    $user_id = $_POST['user_id']; // Use input name to get user id being modify

    // Start by deleting all the roles
    for ($i = 0; $i < $count; $i++) {
        $a = $i + 1;
        // Deleted all roles
        $query2 = "DELETE FROM users_roles WHERE user_id = '$user_id' AND role_id = '$a'";
        _log('$query2: ' . $query2);
        $in_ch2 = mysqli_query($connect, $query2);
    }

    foreach ($_POST['roles_checkbox'] as $selectedOption) {
        //echo $selectedOption . "\n";
        // Insert selected roles
        $query = "INSERT INTO users_roles(user_id, role_id) VALUES ('$user_id', '" . $selectedOption . "')";
        $in_ch = mysqli_query($connect, $query);
    }
    echo "<meta http-equiv='refresh' content='0'>";
    $connect->close();
}
?>

我认为您尝试在重新插入新用户角色之前删除所有当前用户角色的做法是正确的。不过,我想这也是问题所在。

试试这个:

// Start by deleting all the roles
for ($i = 0; $i < $count; $i++) {
    $a = $i + 1;
    // Deleted all roles
    $query2 = "DELETE FROM users_roles WHERE user_id = '$user_id' AND role_id = '$a'";
    _log('$query2: ' . $query2);
    $in_ch2 = mysqli_query($connect, $query2);
}

这样做:

$delete_query = "DELETE FROM users_roles WHERE user_id = '$user_id'";
mysqli_query($connect, $delete_query);

根据评论编辑

知道用户不能有任何角色,您将开始删除初始输入检查 if ($_POST['roles_checkbox']) 并将其重新设置为用户 ID 检查,即 if ($_POST['user_id']) 这允许您继续 运行 其余过程不依赖于角色输入。请参阅下面我更新的示例...

// First check if the request includes a user id
$user_id = !empty($_POST['user_id']) ? (int)$_POST['user_id'] : null;
if ($user_id) {

    // Second, lets delete all existing roles
    $delete_query = "DELETE FROM users_roles WHERE user_id = '$user_id'";
    mysqli_query($connect, $delete_query);

    // Now we check if the request includes any selected role
    if (!empty($_POST['roles_checkbox'])) {

        // This array will hold MySQL insert values
        $insert_values = [];

        // Loop through request values, sanitizing and validating before add to our query
        foreach ($_POST['roles_checkbox'] as $role_id) {
            if ($role_id = (int)$role_id) {
                $insert_values[] = "('{$user_id}', '{$role_id}')";
            }
        }

        // Double check we have insert values before running query
        if (!empty($insert_values)) {
            $insert = "INSERT INTO users_roles(user_id, role_id) VALUES " . implode( ', ', $insert_values );
            mysqli_query($connect, $insert);
        }
    }

    echo '<meta http-equiv="refresh" content="0">';
    $connect->close();
}