Using form_dropdown in codeigniter to populate from the database

in the controller send this:

   $data["fruits"] = $this->db->get('fruits')->result();

Now you could go and loop through each fruit and create a select form input tag and create options with a selected option like this:

    echo "<td><select id='". $fruitbasket->id ."'>";
    echo "<option value=''></option>";
    foreach($fruits $f){
        if($f->id == $fruitbasket->moldiest){
            $selected = " selected=selected ";
        } else {
            $selected = "";
        echo "<option $selected value=" . $f->id . ">" . $f->name . "</option>";
    echo "</select>";

or you could use the form_dropdown helper:

    $fruit_options = array();
    foreach($fruits as $fruit){
    echo "<td>" . form_dropdown('', $fruit_options, $fruitbasket->moldiestfruit,$fruitbasket->id) . "</td>";

The tiny bit of overhead is that codeigniter puts the result in an array of objects rather than an array of arrays which form_dropdown asks for, so the tiny loop is required to create the options variable.

Comments are closed.