我有一个带有多重选择的表单,该表单向用户显示要选择的组的列表,然后将其保存在数据库中。我的目的是,当用户要编辑他的信息时,要选择保存在数据库中的组,不要选择其他组。请查看我的代码并提出建议。
我将保存的组填充到变量中
$groups = array($row['groups']); // This outputs the groupId from the db eg 1,2,3,6
将组填充到多选
<div class="form-group">
<!-- <label>Church Groups: </label> -->
<select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >
<?php
$sql="SELECT ID,UCASE(groupName) AS groupName FROM tblgroups WHERE (congregationId=?)";
$stmt=mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_bind_param($stmt,'i',$congId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
$selected = "";
if(in_array($row['ID'],$groups)){
$selected = "selected";
}
echo '<option value='.$row['ID'].' '.$selected.'>'.$row['groupName'].'</option>';
}
?>
</select>
多数民众赞成在我的代码,但它不起作用。如果保存了列表中的第一个组,则仅选择该组,而其他所有组均保持未选中状态,无论是否在数据库中。
<div class="form-group">
<!-- <label>Church Groups: </label> -->
<select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >
<?php
$sql="SELECT ID,UCASE(groupName) AS groupName FROM tblgroups WHERE (congregationId=?)";
$stmt=mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_bind_param($stmt,'i',$congId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
$selected = "";
if(in_array($row['ID'],$groups)){
$selected = "selected";
}
echo '<option value='.$row['ID'].' '.$selected.'>'.$row['groupName'].'</option>';
}
?>
</select>
使用您的代码,我已取消注释掉您注释掉的行,并引入了一个变量,如果该值不在组中,则该变量将为空,否则它将具有“ selected”值,该变量将实现与selected =“ selelected”相同的功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句