Search code examples
phpcodeignitercodeigniter-3codeigniter-query-builder

How to fetch data from database and display it in a drop down list using Codeigniter


I collect data from the database table and display it in the drop-down list, here's what I've done so far

THIS IS MY CONTROLLER:

public function assign_hostel() {
        $inner_page_title = 'Assign Hostel'; 
        $this->admin_header('Assign Hostel', $inner_page_title);
        $data['hostel'] = $this->hostel_model->get_hostel();    
        $this->load->view('admin/hostel/assign_hostel');
        $this->admin_footer();
    }

THIS IS MY MODEL:

public function get_hostel() { //get all hostel
        $this->db->order_by('hostel_name', 'asc');
        return $this->db->get_where('school_hostel',  array('hostel_name' => 
        $hostel_name)->result();
    }

MY VIEW:

<div class="form-group">
        <label class="form-control-label">Select Hostel</label>
         <select class="form-control" name="state_of_origin" required>
           <option value="">-Select-</option>
             <?php 
             $hostel_name = get_hostel();
             foreach ($hostel_name as $hostel ) { ?>
           <option value="<?php echo $hostel; ?>"><?php echo $hostel; ?></option>
            <?php } ?>
        </select>
</div>

Why am I getting an empty drop-down list?


Solution

  • Hope this will help you :

    Pass $data['hostels'] in your view as given below :

    First your controller assign_hostel should be like this :

    public function assign_hostel() 
    {
        $inner_page_title = 'Assign Hostel'; 
        $this->admin_header('Assign Hostel', $inner_page_title);
        $data['hostels'] = $this->hostel_model->get_hostel();    
        $this->load->view('admin/hostel/assign_hostel' ,$data);
        $this->admin_footer();
    }
    

    Second your view should be like this :

    <div class="form-group">
        <label class="form-control-label">Select Hostel</label>
         <select class="form-control" name="state_of_origin" required>
           <option value="">-Select-</option>
             <?php if ( !empty($hostels)) {
             foreach ($hostels as $hostel ) { ?>
                <option value="<?=$hostel->hostel_name; ?>"><?=$hostel->hostel_name;?></option>
            <?php } }?>
        </select>
    </div>
    

    For more : https://www.codeigniter.com/user_guide/general/index.html