0

I'd like to display all roles from database as check-boxes and check the ones that the current user is already in.

Question: How can I check the check-boxes where the user is already in that role.

<?php
// DB QUERY: get role names
// ------------------------------------------------------------------
$get_roles = mysqli_query($conn, "SELECT RoleName FROM roles")
or die($dataaccess_error);

$get_user_in_roles = mysqli_query($conn, "SELECT RoleName FROM users_in_roles WHERE UserId = $user_id")
or die($dataaccess_error);
// ------------------------------------------------------------------

// user in roles
while($row2 = mysqli_fetch_array($get_user_in_roles))
{
    $user_in_role = $row2['RoleName'];
}

// echo out role names
while($row1 = mysqli_fetch_array($get_roles))
{
    $role_name = $row1['RoleName'];
    echo '<label class="label"><input type="checkbox" name='.$role_name.' class="checkbox">'.$role_name.'</label>';
}
?>

2 Answers 2

1

I would make $user_in_role an array, then change the statement inside the first while loop to $user_in_role[] = $row2['RoleName']; (this appends the role name to the array). Then, when echoing the checkbox, add this between class="checkbox" and the >:

' . (in_array($role_name, $user_in_role) ? ' checked="checked"' : '') . '

Sign up to request clarification or add additional context in comments.

Comments

0
<input checked='checked' type='checkbox' ... />

You can also disable input fields.

<input checked='checked' disabled='disabled' type='checkbox' ... />

Effectively making the check-box marked and disabled.

3 Comments

I'm pretty sure that disabling the checkbox would make that value not get POSTed, so depending on how you handle that it might lead to some weirdness (e.g., is lack of a value equivalent to not being checked?).
@Tom Smilack I generally have a hidden input with the expected value to keep form consistency. Nevertheless it's a good input. Thanks.
@Scott W. sorry by the lack of detail. Though you were looking for general guidance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.