php 在 Codeigniter 中为 foreach() 提供的参数无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18951168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invalid argument supplied for foreach() in Codeigniter
提问by Clfc Developer
I am getting error message: Invalid argument for foreach() in my View. I wanted to display all entries in my mysql table but i kept on getting error message. I am a newbie in Codeigniter and couldn't really figure out how to solve this. The codes are the following: My model (display_branch.php)
我收到错误消息:在我的视图中 foreach() 的参数无效。我想显示我的 mysql 表中的所有条目,但我一直收到错误消息。我是 Codeigniter 的新手,无法真正弄清楚如何解决这个问题。代码如下:我的模型(display_branch.php)
<?php if(!defined ('BASEPATH')) exit ('No direct script access allowed');
class Display_Branch extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function getAll()
{
$this->db->select('bcode, bname, btel, badd');
$this->db->from('branches');
$query = $this->db->get();
if($query->num_rows() == 1)
{
$results = $query->result();
return $results;
}
else
{
return FALSE;
}
}
}?>
My Controller (link_controller.php) *only the snippet.
我的控制器 (link_controller.php) *只有代码片段。
public function insert()
{
$this->load->model('display_branch');
$data['results'] = $this->display_branch->getAll();
$this->load->view('insert_branch');
$this->load->view('navigation');
$this->load->view('content_bc', $data);
$this->load->view('footers');
}
And my view(content_bc.php)
而我的观点(content_bc.php)
<?php
foreach($results as $row)
{
echo '<tr>';
echo '<td>'.$row->bcode.'</td>';
echo '<td>'.$row->bname.'</td>';
echo '<td>'.$row->btel.'</td>';
echo '<td>'.$row->badd.'</td>';
echo '</tr>';
}
?>
Please help me what to do. Thank you.
请帮我做什么。谢谢你。
回答by Sudhir Bastakoti
you need to do a check before starting to iterate for the data, like: model code:
您需要在开始迭代数据之前进行检查,例如:模型代码:
public function getAll() {
$results = array();
$this->db->select('bcode, bname, btel, badd');
$this->db->from('branches');
$query = $this->db->get();
if($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
view code:
查看代码:
if( !empty($results) ) {
foreach($results as $row) {
echo '<tr>';
echo '<td>'.$row->bcode.'</td>';
echo '<td>'.$row->bname.'</td>';
echo '<td>'.$row->btel.'</td>';
echo '<td>'.$row->badd.'</td>';
echo '</tr>';
}
}
回答by Misterwyz
The query in your model is returning either string or object data, instead of an array. The 'foreach' loop function accepts an array as its first argument.
模型中的查询返回字符串或对象数据,而不是数组。'foreach' 循环函数接受一个数组作为它的第一个参数。
回答by Yazu Idoari
I think this code modular:
我认为这个代码模块化:
public function getAll() {
$this->db->select('bcode, bname, btel, badd');
$this->db->from('branches');
$query = $this->db->get('branches');
return $this->db->query($query)->result_array();
}

