can't load field in database to combobox

Viewed 48

I'm newbie in codeigniter, i want to make one field of database can be diplayed in combobox but, i just got this error.

A PHP Error was encountered Severity: Notice Message: Array to string conversion Filename: mahasiswa/ubah.php Line Number: 30 backtrace

Controller

public function ubah($id)
{
    $data['judul'] = 'Form Ubah Data Mahasiswa';
    $data['mahasiswa'] = $this->Mahasiswa_model->getMahasiswaById($id);
    $data['jurusan'] = $this->Jurusan_model->getAllJurusan();
    $this->form_validation->set_rules('nama', 'Nama', 'required');
    $this->form_validation->set_rules('nim', 'NIM', 'numeric|required');
    $this->form_validation->set_rules('email', 'Email', 'required');

    if ($this->form_validation->run()== FALSE) {
        $this->load->view('templates/header', $data);
        $this->load->view('mahasiswa/ubah', $data);
        $this->load->view('templates/footer');
    }else{
        $this->Mahasiswa_model->ubahDataMahasiswa();
        $this->session->set_flashdata('flash', 'Diubah');
        redirect('mahasiswa');
    }
}

Model

class Jurusan_model extends CI_model
{

    public function getAllJurusan()
    {
        $this->db->select('jurusan');
        return $this->db->get('mahasiswa')->result_array(); 
    }
}

View

<div class="form-group">
  <label for="jurusan">Jurusan</label>
  <select class="form-control" id="jurusan" name="jurusan">
    <?php foreach($jurusan as $j) : ?>
      <option value="<?= $j; ?>"><?= $j;?></option>
    <?php endforeach;?>
  </select>
</div>
2 Answers

You should use Codeigniter Form Helper to do that : https://www.codeigniter.com/user_guide/helpers/form_helper.html#form_dropdown

<?php
// Get Jurusan (Add more fields on $this->db->select('id, jurusan'))
$jurusan = $this->jurusan_model->getAllJurusan();

// Prep Options (I dont know "mahasiswa" table structure is, but at least need 2 columns, like "ID" and "Text / Name")
foreach ($jurusan as $j) {
  $options[$j['jurusan_id']] = $j['jurusan_name'];
}

// Generate Dropdown
echo form_dropdown('jurusan', $options);
?>

Your data in getAllJurusan() is return as result_array

So after foreach you need to select the key.

<?php foreach($jurusan as $j) : ?>
    <option value="<?= $j['jurusan']; ?>"><?= $j['jurusan'];?></option>
<?php endforeach;?>
Related