how to retrieve checked value from database in codeigniter

i need to show checked values in checkbox from a db column (named "course")

my controller

public function CheckBoxUpdate($id=0)
    $this->load->view('site' ,$data);

My model

public function getInvoice($id=0)
    return $this->db->select('*')
            ->where('id', $id)

My view



  print_r ($course);


<input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="course[]" value="<?php echo $course_taken['course'];?>"   >
<label class="form-check-label" for="inlineCheckbox1"><?php echo $course_taken['course'];?></label>

My database

id       course
===     ========
1       option1,option2

How can i display these to selected item in checkbox as checked in codeigniter

3 answers

  • answered 2019-03-14 01:28 curiosity

    Here's i can do for you.. try it.

    $courses=array('option1','option2'); //type manually all your course option
    $purposesFromDB= $pr['purpose'];
    $coursesFromDBArray=explode(',',$coursesFromDB); //explode data from database 
       foreach($purposesFull as $opt){
       $checked = in_array($opt,$purposesFromDBArray) ? 'checked' : ''; //check if it's in the array
       echo '<input type="checkbox" name="options[]"'.$checked.'>'.$opt;

  • answered 2019-03-14 04:14 Danish Ali

    Do like this

    <?php if(count($course) > 0): 
          foreach($course as $row):?>
        <input class="form-check-input" type="checkbox" id="inlineCheckbox1" name="course[]" value="<?= $row ?>"  <?php if($row == 'course-name'){ echo 'checked="checked"';}?> >
        <label class="form-check-label" for="inlineCheckbox1"><?= $row ?></label>
    <?php endforeach; endif; ?>

  • answered 2019-03-14 04:55 Hasta Dhana

    I assume you have a set of the whole checkboxes named $checkboxes like this :

    $checkboxes = array(
        '0' => 'option0', 
        '1' => 'option1', 
        '2' => 'option2', 
        '3' => 'option3', 
        '4' => 'option4', 
        '5' => 'option5', 

    Looking at your controller, I assume you have all the checked item as $course_taken.
    You could display both the checked and unchecked item like this :

    $course = explode(",",$course_taken['course']);
    foreach ($checkboxes as $key => $value) {
        <input class="form-check-input" type="checkbox" id="inlineCheckbox<?php echo $key ?>" name="course[]" value="<?php echo $value ?>" <?php echo in_array($value, $course)?'checked="checked"':'' ?> >
        <label class="form-check-label" for="inlineCheckbox<?php echo $key ?>"><?php echo $value ?></label>