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>';
}
?>
I would make
$user_in_rolean 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 betweenclass="checkbox"and the>:' . (in_array($role_name, $user_in_role) ? ' checked="checked"' : '') . '