Welcome Guest, Not a member yet? Register   Sign In
Populate a Drop down from Database
#1

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']); ?>
Reply
#2

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.
Reply
#3

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); ?>
Reply
#4

(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?
Reply
#5

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB