![](/img/trans.png)
[英]Undefined variable & Invalid argument supplied for foreach() in CodeIgniter
[英]undefined variable Codeigniter and invalid argument supplied foreach read database
我正在按照说明从表中获取整个记录,并将它们加载到html表中。 这是模型
private $namatabel;
public function __construct() {
parent::__construct();
$namatabel='ms_kategori_material';
}
function read()
{
$sql = $this->db->get($this->namatabel);
if($sql->num_rows() > 0)
{
foreach($sql->result() as $row)
{
$data[] = $row;
}
return $data;
}
else
{
return null;
}
}
然后在控制器上使用read()
函数
public function __construct() {
parent::__construct();
$this->load->model('m_kategorimaterial');
}
function index()
{
$data['c_row'] = $this->m_kategorimaterial->read();
//pass the c_row into the views
$this->load->view('v/vkategorimaterial', $data);
}
在视图上显示它们
<?php
$no = 1;
foreach ($c_row as $row) { ?>
<tr id="row">
<td id="no"><?php echo $no;?></td>
<td id="judul"><?php echo $row->Kode_Kategori_Material_Jasa;?></td>
<td id="kategori"><?php echo $row->Nama_Material_Jasa;?></td>
</tr>
<?php
$no++;
}
?>
但是然后我得到一个错误,说未定义的变量c_row
和foreach()
提供了无效的参数。 我以为我已经通过c_kategorimaterial/index
发送了c_row
变量并复制了粘贴foreach
语句。 什么地方出了错 ?
1)通过使用print_r($data)
来检查数据是否正确。 如果出错,则您可能在查询中丢失了某些内容。
2)如果您完美地获得了数据库数据,则只需在模型中更改返回数组的名称即可。
function read()
{
$sql = $this->db->get('ms_kategori_material');
if($sql->num_rows() > 0)
{
foreach($sql->result() as $row)
{
$c_row[] = $row;
}
return $c_row; //comment this return part while debugging
// print_r($c_row);
//exit;
}
else
{
return null;
}
}
如果您打印数据数组以确切了解该数组中的内容,那会更好。 尝试使用以下格式,可能会有所帮助
function getPosts() {
$query = $this->db->get('posts');
$posts = array();
foreach ($query->result() as $row) {
$posts[] = array(
'id' => $row->id,
'title' => $row->title,
'content' => $row->content
);
}
return $posts;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.