PHP dynamic checkboxes

好久不见. 提交于 2019-12-11 17:48:16

问题


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>';
}
?>

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




回答2:


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



来源:https://stackoverflow.com/questions/4074846/php-dynamic-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!