我有一个带有2个表的简单数据库:
1. active_services 2. devices
------------------ ------------------------------
id | service id | active_services_value
------------------ ------------------------------
1 | AD 1 | AD,DNS,DHCP
2 | FTP 2 | FTP,SMB
3 | DNS 3 | FTP
4 | DHCP 4 |
5 | SMB 5 | AD Backup
6 | AD Backup
我将active_services中的service列的值用作表单的复选框,该表单会将检查后的值发布到表设备的active_service_values列。我的代码如下:
<?php
if($active_services_value != ""){
// Need to generate a list of checkboxes from active_services but
// for each value in the active_services_field coresponding
// to the searched id (e.g for id 1, value1 = AD, value2 = DNS,
// value3 = DHCP ) set the checkboxes as checked
} else {
// display the service in active_services as checkboxes
$q = "SELECT * from active_services";
$r = mysqli_query($dbc, $q);
while($list = mysqli_fetch_assoc($r)){
?>
<div class="col-xs-4"><input type="checkbox" name="checkboxvar[]" value="<?php echo $list['service']; ?>"><?php echo $list['service'];?>
</div>
<?php } } ?>
</div>
?>
我的问题是:
如何显示“已选中”复选框,使用户可以取消选中某些复选框,同时还显示其余未选中的复选框,从而使用户可以检查新选项?
预先感谢大家的帮助。
您可以通过将checked
属性添加到输入字段来将复选框标记为“已选中” 。因此,如果您从数据库中检索选定项目的列表,则可以使用这些项目来确定是否应将选中的属性添加到输入字段。
它将变成这样:
<?php
$stmt = $dbc->prepare("SELECT active_services_value FROM devices WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($serviceList);
$stmt->fetch();
//transform the list of services into an array
$services = explode($serviceList, ",");
$q = "SELECT * from active_services";
$r = mysqli_query($dbc, $q);
while($list = mysqli_fetch_assoc($r)){
?>
<div class="col-xs-4">
<input type="checkbox" name="checkboxvar[]"
value="<?php echo $list['service'];?>"
<?php if (in_array($list['service'], $services) { echo "checked"; } ?>>
<?php echo $list['service'];?>
</div>
<?php } } ?>
</div>
对于您的问题,我还有一些其他需要改进的地方:
device,service
对)active_services
表中服务的ID并将其设置为外键,而不是使用devices表中的服务名称。这将提高性能并保证表中的一致性(即,如果设置正确,将不可能在devices表中使用不存在的服务)。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句