我有以下简单代码: 型号:
function get_last_ten_entries()
{
$this->db->get('property');
}
Controller :
public function load_recent()
{
$data['info'] = $this->propertymodel->get_last_ten_entries();
$this->load->view('load_property', $data);
}
查看:
<?
echo $data['id'];
?>
这是行不通的。我确定我做错了什么,因为显示的错误是
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/load_property.php
Line Number: 2
Property 是数据库中的一张表,其中有一个名为id 的字段。怎么了?
谢谢大家
最佳答案
要修复错误,您需要在 View 中使用 $info
,而不是 $data
,因为 Controller 中的数组索引对应于您的变量查看。
$this->db->get('property')
返回表 property
中的所有行,但您的函数名称暗示您正在尝试获取最后 10 个条目。我建议你阅读 CodeIgniter's Active Record documentation了解更多信息。您还需要返回
您的查询。
您需要根据查询生成结果。 CodeIgniter's Query Results documentation提供有关如何使用查询结果的有用信息。您想要实现的目标有点模糊,但您的代码可能如下所示:
型号
function get_last_ten_entries()
{
return $this->db->get('property'); //Perform query (you'll need to update to select what you actually want from you database)
}
Controller
public function load_recent()
{
$data['last_entries'] = $this->propertymodel->get_last_ten_entries();
$this->load->view('load_property', $data);
}
查看
foreach ($last_entries->result_array() as $entry)
{
echo $entry['id'];
}
或者,如果您宁愿使用对象而不是数组:
foreach ($last_entries->result() as $entry)
{
echo $entry->id;
}
关于php - CodeIgniter 选择并在 View 中显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446334/