未定义的变量:尝试访问单行时CodeIgniter上的行

时间:2013-04-29 08:25:14

标签: php codeigniter activerecord

我有一个宠物数据库,基本上我想通过它的ID查看宠物的详细信息。这是我的Controller方法:

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');
}

以下是抓取相关行的AnimalsModel代码:

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查询,并且它可以工作,它为我提供了正确的行。

编辑: 我刚刚继续在$ row对象上执行了var_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一直在抱怨Undefined variable: row :(

2 个答案:

答案 0 :(得分:0)

请试试这个

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');
}

现在尝试访问视图中的数据。

答案 1 :(得分:0)

您可以使用

检查CI中的最后一个查询
    <pre> <?php print_r($this->db->last_query()) ?> </pre>

然后复制过去并在phpMyadmin或任何你使用的任何地方尝试。

为了更好的结果/审核/维护您的MODEL代码应该看起来像这样

  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!!";
}

}

最后一件事是: 在CI中,最好使用如下名称:    mymodelname_model不是myModelNameModel 在你的情况下    animals_model not animalsmodel

这就是CI用户的方式:)

享受您的代码