CodeIgniter Forums
Fill dropdown from database - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Fill dropdown from database (/thread-33780.html)



Fill dropdown from database - El Forum - 09-08-2010

[eluser]rijobo[/eluser]
Can somebody tell me how I can fill a dropdown in a form from a database?


Fill dropdown from database - El Forum - 09-08-2010

[eluser]flaky[/eluser]
Code:
//model
class Some_model extends Model {
    
    public function __construct() {
        parent::__construct();
    }
    
    public function get_dropdown() {
        $result = $this->db->select('id, name')->get('table_name')->result_array();
        
        $list = array();
        foreach($result as $r)
            $list[$r['id']] = $r['name'];
            
        return $list;
    }
}

.
.
.
//controller

class Test extends Controller {
    
    public function __construct() {
        parent::__construct();
        
        //Load models
        $this->load->model('some_model');
    }
    
    public function index() {
        $data['dropdown'] = $this->some_model->get_dropdown();
        $this->load->view('some_view', $data);
    }

}

.
.
.
//View
Some dropdown: <?php echo form_dropdown('some_dropdown', $dropdown); ?>



Fill dropdown from database - El Forum - 09-08-2010

[eluser]CroNiX[/eluser]
You just need to make an array of key/value pairs.
Code:
$dropdown_data[0] = 'Make a selection';
$dropdown_data[3] = 'John';
$dropdown_data[27] = 'Mary';

//Then
<?php echo form_dropdown('some_dropdown', $dropdown, 3); ?>
//produces:
<select name="some_dropdown">
    <option value="0">Make a selection</option>
    <option value="3" selected="selected">John</option>
    <option value="27">Mary</option>
</select>