CodeIgniter Forums
Populate a Drop down from Database - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11)
+--- Thread: Populate a Drop down from Database (/showthread.php?tid=64776)



Populate a Drop down from Database - ugyenlingpa - 03-24-2016

I am new to CI. I am trying to populate a Country from Database to a Drop down in View . After passing a Array Data how do i show in drop down.

Following are the Code:
1. controller Country
Code:
public function get_country_dropdownlist()
   {
      $data['country'] = $this->Country_model->get_country_dropdownlist();
      //print_r($data);
      //die;
       $this->load->view('country_list_view', $data);
   }

2. Model
Code:
public function get_country_by_id($country_id)
   {
        //return $this->db->insert_id();
       $this->db->select("country_id,country_name");
       $this->db->from('country');
       $this->db->where(['country_id'=>$country_id]);
       $query = $this->db->get();
       return $query->result();
   }

3.View
Code:
 <?php echo form_dropdown('country_id',$data['country']); ?>



RE: Populate a Drop down from Database - Wouter60 - 03-25-2016

The $data array that you pass to the view, is automatically extracted bij CI. As a result, the view will not know the array $data, but it does know the variables that are part of it.
You can populate the dropdown with this:
PHP Code:
<?php echo form_dropdown('country_id',$country);?>

The form helper will build a <select></select> element. The array keys in $country will be used as values of the option elements, and the array values will be visible as text in the dropdown.

Hope this will help you.


RE: Populate a Drop down from Database - michalsn - 03-25-2016

Controller is fine, but your model and view not.

Model:
PHP Code:
public function get_country_dropdownlist()
{
 
      $results $this->db->select('country_id, country_name'); 
 
                          ->get('country')
 
                          ->result_array();

 
      return array_column($results'country_name''country_id');


View:
PHP Code:
<?php echo form_dropdown('country_id'$country); ?>



RE: Populate a Drop down from Database - Tecvid - 03-25-2016

(03-25-2016, 08:58 AM)michalsn Wrote: Controller is fine, but your model and view not.

is array_column() faster than where clause? coz without where query takes all rows from db, isnt it bad for db?


RE: Populate a Drop down from Database - michalsn - 03-25-2016

We want to populate a dropdown with list of countries so I don't see a point to select country by country_id. If you're worry about DB hit, you can always cache the result.

Also, array_column have nothing to do with filtering query result. It just transform result to format, that can be used by form_dropdown function.