Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fetch field values from database and set in dropdown using codeigniter

I am new in CodeIgniter and working on a application in which i have a form. In this form I have a dropdown. I have some values in a column of database. I want these values in the dropdown, I have no idea how to do it.

My view is:

<tr>
    <td>Moderator :</td>
    <td><label for="select"></label>
    <select name="mod" tabindex="1" >
    <!--values i want from database-->
    </select>
    </td>
</tr>
like image 721
Jay Avatar asked Mar 09 '26 16:03

Jay


1 Answers

This example is for a country table in our application, the table contains, id, symbol, name

Controller:

$data['countries']=$this->countries_model->get_countries();
$this->load->view('countries',$data);

Model:

    function get_countries()
    {
        $query = $this->db->get('countries');
            if ($query->num_rows >= 1)
            {
                foreach($query->result_array() as $row)
                {
                    $data[$row['countryId']]=$row['countryName'];
                }
                return $data;
            }
    }

It returns an array like:

$id=>$name
0=>Canada
1=>United States

View:

echo form_dropdown('countries',$countries); //ci syntax

Or:

<select name="country">
<?php
    foreach($countries as $country)
    {
       echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
    }
?>
</select>
like image 109
Rick Calder Avatar answered Mar 11 '26 04:03

Rick Calder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!