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

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
public function get_country_dropdownlist()
      $data['country'] = $this->Country_model->get_country_dropdownlist();
       $this->load->view('country_list_view', $data);

2. Model
public function get_country_by_id($country_id)
        //return $this->db->insert_id();
       $query = $this->db->get();
       return $query->result();

 <?php echo form_dropdown('country_id',$data['country']); ?>

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.

Controller is fine, but your model and view not.

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

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

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

(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?

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.

Theme © iAndrew 2016 - Forum software by © MyBB