开发者

PHP dynamic checkboxes

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_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"' : '') . '


<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜