Dhe*_*212 3 php arrays codeigniter
我是 codeigniter 的新手,只是我收到此错误:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/coba.php
Line Number: 52
Run Code Online (Sandbox Code Playgroud)
但我仍然无法解决它。这是我在控制器上的代码:
public function getvalue()
{
$result = $this->admin_model->harga();
$data = array(
'harga' => $result,
);
if ($this->input->post('btnKirim')==true) {
$data['nama']=$this->input->post('nama');
$data['tgl_masuk']=$this->input->post('tgl_masuk');
$data['tgl_ambil']=$this->input->post('tgl_ambil');
$data['berat']=$this->input->post('berat');
$data['status']=$this->input->post('status');
}
$data['judul'] = 'Halaman Pegawai';
$data['content'] = 'coba';
$this->load->view('template/index',$data);
}
Run Code Online (Sandbox Code Playgroud)
我的模型的代码:
public function harga(){
$query= $this->db->query('SELECT harga from satuan');
return $query->result();
}
Run Code Online (Sandbox Code Playgroud)
这是我的 view.php,我在其中收到此错误消息:
<div class="form-group">
<label for="total" class="control-label">Total Harga</label>
<div>
<input name="total" id="total" type="numeric" class="form-control" value="<?php echo $harga; ?>" readonly='total'>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
为什么我会收到此消息,我该如何解决?
方法result返回对象数组或空数组。无论哪种方式,方法harga都会返回一个数组。
由于您使用该结果来填充字段的值,因此不清楚您是否真的想要表中的所有结果,或者只是一些特定的结果,甚至可能只是一个结果。无论您想要什么,您都需要将其转换为标量值,以便能够echo在没有警告的情况下使用。
可以迭代返回的结果,因此您可以执行以下操作:
public function harga() {
// Since your HTML containts 'Total harga', I'm assuming you
// have multiple results and you need to add them all up
$result = 0
foreach($query->result() as $row) {
$output += $row->harga;
}
return $result;
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要一个结果,请考虑使用$query->row()从表中获取一行(更好的是,在 SQL 查询中使用limitor )。where
要完全了解您的问题是什么,请查看文档。