如何创建复选框检查codeigniter中的数据库中是否存在值?

时间:2017-07-15 07:56:08

标签: php codeigniter

代码:

<?php
    foreach ($college_id as $fetch) 
    {
        $facility=explode(",",$fetch['facilities']);
        foreach ($facility as $key) 
        {
            $facilities = $key;
        }
    }
?>

<input type='checkbox'  name='facilities[]' value='Gym' <?php if(in_array("Gym",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Gym
<input type='checkbox'  name='facilities[]' value='Boys Hostel' <?php if(in_array("Boys Hostel",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Boys Hostel
<input type='checkbox'  name='facilities[]' value='Girls Hostel' <?php if(in_array("Girls Hostel",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Girls Hostel
<input type='checkbox'  name='facilities[]' value='Scholarship' <?php if(in_array("Scholarship",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Scholarship

在这段代码中,我有多个复选框,数值存在于数据库中。现在,如果数据库中存在值,我想检查复选框。那么,我该怎么办呢?请帮帮我。

谢谢

3 个答案:

答案 0 :(得分:2)

您可以尝试使用此代码。

<?php
    $college_id = array('facilities'=> array('Gym', 'Boys Hostel'));
?>

 <input type='checkbox'  name='facilities[]' value='Gym' <?php if(in_array("Gym",$college_id['facilities'])) { ?> checked="checked" <?php } ?>> &nbsp; Gym
 <input type='checkbox'  name='facilities[]' value='Boys Hostel' <?php if(in_array("Boys Hostel",$college_id['facilities'])) { ?> checked="checked" <?php } ?>> &nbsp; Boys Hostel
<input type='checkbox'  name='facilities[]' value='Girls Hostel' <?php if(in_array("Girls Hostel",$college_id['facilities'])) { ?> checked="checked" <?php } ?>> &nbsp; Girls Hostel
<input type='checkbox'  name='facilities[]' value='Scholarship' <?php if(in_array("Scholarship",$college_id['facilities'])) { ?> checked="checked" <?php } ?>> &nbsp; Scholarship

将检查健身房和男孩宿舍复选框。

干杯!!

答案 1 :(得分:1)

试试这个。我认为它有效。

<input type="checkbox" name="facilities[]"  value="Gym" <?= 
  if(in_array("Gym",$college_id['facilities']) == "Gym") ? "checked" : "" ?>>Gym

答案 2 :(得分:0)

在您的代码中,您声明$facilities = $key;这意味着$ facility不是数组。修复是这样的:

<?php
$facilities = array();
foreach ($college_id as $fetch) 
{
    $facility=explode(",",$fetch['facilities']);
    foreach ($facility as $key) 
    {
        $facilities[] = $key;
    }
}
?>

<input type='checkbox'  name='facilities[]' value='Gym' <?php if(in_array("Gym",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Gym
<input type='checkbox'  name='facilities[]' value='Boys Hostel' <?php if(in_array("Boys Hostel",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Boys Hostel
<input type='checkbox'  name='facilities[]' value='Girls Hostel' <?php if(in_array("Girls Hostel",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Girls Hostel
<input type='checkbox'  name='facilities[]' value='Scholarship' <?php if(in_array("Scholarship",$facilities)) { ?> checked="checked" <?php } ?>> &nbsp; Scholarship