Php 未定义变量:尝试访问单行时CodeIgniter上的行
我有一个宠物数据库,基本上我想通过ID查看宠物的详细信息。以下是我的控制器方法:Php 未定义变量:尝试访问单行时CodeIgniter上的行,php,codeigniter,activerecord,Php,Codeigniter,Activerecord,我有一个宠物数据库,基本上我想通过ID查看宠物的详细信息。以下是我的控制器方法: public function details() { $this->load->model('animalsmodel'); $row = $this->animalsmodel->details($this->uri->segment(3)); $this->load->view('shared/header'); $this-&g
public function details()
{
$this->load->model('animalsmodel');
$row = $this->animalsmodel->details($this->uri->segment(3));
$this->load->view('shared/header');
$this->load->view('animals/details', $row);
$this->load->view('shared/footer');
}
下面是获取相关行的animalmodel
代码:
function details($animalId) {
$q = $this->db->query('SELECT Animals.Name, Animals.DateAdmitted, Animals.FoundDescription, Animals.Description, Animals.Neutered, Animals.DateNeutered, Types.Name AS Type, Healthchecks.CheckInfo FROM Animals LEFT JOIN Types ON Animals.TypeId = Types.TypeId LEFT JOIN Healthchecks ON Animals.HealthcheckId = Healthchecks.HealthcheckId WHERE Animals.AnimalId = ?', $animalId);
if ($q->num_rows() > 0)
{
$row = $q->row();
return $row;
} else
{
echo "No Results Man!!";
}
}
我已经在phpMyAdmin中手动运行了MySQL查询,它运行正常,它为我找到了正确的行
EDIT:我刚刚在$row对象上执行了var\u dump()
,得到了以下结果:
object(stdClass)#17 (8) { ["Name"]=> string(6) "Quemby" ["DateAdmitted"]=> string(10) "2013-01-28" ["FoundDescription"]=> string(94) "The story of how I got to be here. Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor" ["Description"]=> string(65) "massa non ante bibendum ullamcorper. Duis cursus, diam at pretium" ["Neutered"]=> string(1) "0" ["DateNeutered"]=> string(10) "0000-00-00" ["Type"]=> string(3) "Dog" ["CheckInfo"]=> string(26) "a, facilisis non, bibendum" }
看来我已经排好了!但是为什么CI总是抱怨未定义变量:row
:(请试试这个
public function details()
{
$this->load->model('animalsmodel');
$row = $this->animalsmodel->details($this->uri->segment(3));
$data['row'] = $row;
$this->load->view('shared/header');
$this->load->view('animals/details', $data);
$this->load->view('shared/footer');
}
现在尝试访问视图中的数据。您可以使用
<pre> <?php print_r($this->db->last_query()) ?> </pre>
}
最后一件事是:
在CI中,最好使用以下名称:
mymodelname\u模型不是myModelNameModel
就你而言
动物模型而非动物模型
CI用户就是这样做的:)
享受你的代码请打印$row并检查它是否正确?首先打印:$q->num_rows();检查是否大于0?@Praveen和Veekay:Q已更新。有效!非常感谢Praveen。你能解释一下为什么这个有效而我的无效吗?在CI中,传递的对象必须始终被称为$data且类型为array,这是一种惯例吗?阅读本文,您将了解这一点。你仍然有疑问,请给我留言,我会回复你的。
function details($animalId) {
$this->db->select('Animals.Name, Animals.DateAdmitted, Animals.FoundDescription,...');
$this->db->where('AnimalId', $animalId);
$this->db->join('Types' , 'Types.TypeId = Animals.TypeId' , 'left');
$this->db->join('Healthchecks', 'Healthchecks.HealthcheckId = Animals.HealthcheckId', 'left');
$this->db->from('Animals');
$q = $this->db->get();
if ($q->num_rows() > 0)
{
$row = $q->row();
return $row;
} else
{
echo "No Results Man!!";
}