我是Codeigniter的新手,我想使数据库的一个字段可以在组合框中显示,但是,我刚遇到此错误。
遇到PHP错误 严重程度:注意 消息:数组到字符串的转换 文件名:mahasiswa / ubah.php 行号:30 backtrace
控制器
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');
}
}
模型
class Jurusan_model extends CI_model
{
public function getAllJurusan()
{
$this->db->select('jurusan');
return $this->db->get('mahasiswa')->result_array();
}
}
查看
<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>
答案 0 :(得分:0)
您应该使用Codeigniter Form Helper来做到这一点: 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);
?>
答案 1 :(得分:0)
您在getAllJurusan()
中的数据将以result_array
的形式返回
因此在foreach之后,您需要选择密钥。
<?php foreach($jurusan as $j) : ?>
<option value="<?= $j['jurusan']; ?>"><?= $j['jurusan'];?></option>
<?php endforeach;?>