将所选值绑定到php中的复选框 [英] Bind the selected values to the checkbox in php
问题描述
我有一个下面提到的php代码段
I have a php code snippet mentioned below
<?php $query = "SELECT * FROM Qualification";
$result = mysqli_query($dbcon,$query);
while($row=mysqli_fetch_array($result)){
?>
<input type='checkbox' value='"<?php $row['Id'] ?> "' name='Qualification[]' /><?php $row['Description'] ?><br>
<?php } ?>
以上代码用于显示数据库中的所有资格。
This above Code is used to Display all the qualification from the databases .
输出将为
[] Teacher
[] Engineer
[] Doctor
[] Banker etc..
现在说我已经选中了3个复选框老师,工程师,医生。
Now say i have checked 3 checkboxes Teacher,Engineer,Doctor.
foreach($_POST['Qualification'] as $Qualification)
{
$AllQualification .=$Qualification.",";
}
$AllQualification ="1,2,3,"
所以我将值的ID连接成一个字符串并将其存储为
1,2,3,
So i am concatenating the ID of the values into a string and store it in database as 1,2,3,
现在,我需要再次将数据绑定到该复选框。当我检索选定的限定条件时,它会给出1,2,3
Now i need to bind the datas again to that checkbox. When i am retriving the selected qualification it gives 1,2,3,
现在如何将所选值绑定到复选框。
Now How to bind the selectedvalues to the checkbox.
我需要的输出是老师,工程师,医生,应检查
,银行家应放开支票。
The output i need is teacher,Engineer,Doctor should be checked and banker should be uncheked.
任何帮助表示赞赏。
推荐答案
您可以这样做
将字符串分解为数组
$AllQualification ="1,2,3,";
$selected = explode(",", $AllQualification);
$selected = array_filter($selected);
//print_r($selected);
使用in_array您可以检查是否已选中
using in_array you can check whether it is checked
<?php $query = "SELECT * FROM Qualification";
$result = mysqli_query($dbcon,$query);
while($row=mysqli_fetch_array($result)){
?>
<input type='checkbox' value='"<?php $row['Id'] ?> "' name='Qualification[]'
<?php if (in_array($row['Id'], $selected)){ echo "checked" } ?> /><?php $row['Description'] ?><br>
<?php } ?>
检查此链接 http://sandbox.onlinephpfunctions.com/code/ae6bbfc6bd0ad84ddceadeac608fa6747de41274
这篇关于将所选值绑定到php中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!