black_belt
black_belt

Reputation: 6799

How to populate dropdownlist from database in Codeigniter?

I have two tables: 1. STUDENT- fields are- (studentid,studentname,batch) 2. BATCH- fields are- (batchid,batchname)

I want to populate a dropdown list from the field "batchname" ( from the table "BATCH") and have the batchname selected based on the field-"batch" (from the table "Student")

My controller -

function update($id){
$this->load->model('mod_studentprofile');
$data['query']= $this->mod_studentprofile->student_get($id); //to retrieve information from the table "STUDENT" 
$data['query']= $this->mod_studentprofile->batch_get();

$data['main_content']='update_studentprofile';
$this->load->view('includes/template',$data);
}

My model -

 function batch_get()
{
  $query = $this->db->get('batch');
  return $query->result();

}    

Now, I cannot figure out how to populate the dropdown in the "View". Would you please kindly help me with this?

Thanks in Advance.

Upvotes: 0

Views: 6799

Answers (2)

John Corry
John Corry

Reputation: 1577

See Jamie Rumbelow's 'MY_Model' class, he has a method that does exactly what you're describing.

https://github.com/jamierumbelow/codeigniter-base-model/blob/master/core/MY_Model.php

Upvotes: 0

Nexerus
Nexerus

Reputation: 1088

You need to put the options you want displayed in the drop down into an array, like so

$options = array(
  'red'   => 'Red',
  'green' => 'Green',
  'blue'  => 'Blue',
);

// The params here are:
// 'color'    => name of the drop down
// '$options' => options for the drop down
// 'red'      => the selected value of the drop down
echo form_dropdown('color', $options, 'red');

What I would do is create a function in my model, say $model->dropdown_options() and use that to get the rows from the database and put them into an array.

Upvotes: 2

Related Questions