• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2 column table to form_dropdown array

I have a simple 2 column table

ID name
1  Bay-1
2  Bay-2
3  Admin

Id like to enter this into an array for use in form_dropdown() so i get this result

<option value="1">Bay-1</option>
<option value="2">Bay-2</option>
<option value="2">Admin</option>

Is there a simplified way to do this?

Something like this may work.

In your model:
function get_names() {
   $names= array();
   $query = $this->db->get('table_name');
   if($query->num_rows() > 0) {
      foreach($query->result_array() as $name) {
         $names[] = $name;
   return $names;

Your controller:
$data['names'] = $this->Model_Name->get_names();
$this->load->view('view_name', $data);

Your view:
foreach($names as $name) {
   echo "<option value='{$name['id']}'>{$name['name'}</option>";

Not what I had in mind, I do the same thing a bit differently in order to keep the view clean and use the helper form_dropdown() main difference is my model contains this

$names[$name['id']] = $name['name'];

In that case once you create the $names array in the model and pass it to the view you can just load it into the form helper.

echo form_dropdown('dropdown_name', $names, 'selected_value');

deleted comment

Nevermind that should amount to the same thing had a brain fart there.

its a 'key' => 'value' array

Once you have that associative array though you should be able to just pass it to the form_dropdown() function as described above.

yeah was just wonder if there was an easy way to just get the data from the database in that format
where can i read up on how many-to-one relational tables are done in codeignighter
or do I code them manually with sql commands?

Nope, even using straight php/mysql you have to loop over it to get it in that format.

I just create a helper, array_to_dropdown($array, $key_field, $value_field, $default_value), where I can pass it the database result array (or any array), the field I want to use for the 'id' index, the key for the 'text' part, and an optional default first value, and it loops over the array creating the new desired array and returning it.

no problem, all done, made my own function

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.