How to get data on database and display in "select" dropdown in view (Codeigniter)

13,136

Try this:

Model:

function getbanklist() {
    $this->db->select("id,bank");
    $this->db->from('bank');
    $query = $this->db->get();
    return $query;
}

In your view:

<select name="bank">
<?php foreach($bankdata->result() as $bank){ ?>
    <option value="<?php echo $bank->id ?>"><?php echo $bank->bank ?></option>
<?php } ?>
</select>
Share:
13,136
Brian Luna
Author by

Brian Luna

Updated on June 04, 2022

Comments

  • Brian Luna
    Brian Luna almost 2 years

    I am a newbie to CodeIgniter, I have created a simple app that will fetch data from database and then display it in a <SELECT> dropdown. I'm trying to get data from a specific field from database to my view. So far, I have tried the code below (not working):

    My model (datamodel.php),

    function getbanklist() {
        $banklist = array();
        $this->db->select("id, bank");
        $this->db->from('bank');
        $query = $this->db->get();
    
        if ($query->num_rows >= 1){
            foreach($query->result_array() as $row){
                $banklist[$row['id']]=$row['bank'];
            }
            return $banklist;
        }
    }
    

    My controller (home.php),

    function index(){
        $data['bankdata'] = $this->datamodel->getbanklist();
        $this->load->view('viewdata', $data);
    }
    

    My view (viewdata.php),

    <tr>
        <th>BANK</th>
        <td>
            <div class="containers">
                <select name="bank">
                <?php foreach($bankdata as $bank){
                    echo '<option value="'.$bank['id'].'">'.$bank['bank'].'</option>';
                } ?>
                </select>
            </div>
        </td>
    </tr>
    

    My database structure (see here),

    id    bank
    ------------
    0     Bank 1
    1     Bank 2
    2     Bank 3
    3     Bank 4
    4     Bank 5
    
  • Brian Luna
    Brian Luna almost 9 years
    I got error, it shows error : Call to a member function result() on a non-object in
  • Kavin Smk
    Kavin Smk almost 9 years
    did you change your model??
  • Brian Luna
    Brian Luna almost 9 years
    yes. I did. maybe I'm messing up with my code. I'll check all. thanks
  • Brian Luna
    Brian Luna almost 9 years
    it works. I messed up with my old code. thanks @KavinSmk
  • raja
    raja about 7 years
    It is not loading dropdown list in view page.