未定义的变量:r在非对象上调用成员函数result()

时间:2015-10-05 08:37:01

标签: php codeigniter

  

模型

public function getDepartmentIdForName($id)
{

    $this->db->select("deptName,deptInfo");
    $this->db->from('departmentinfo');
    $this->db->where('id',$id);
        $query = $this->db->get();

        if($query->num_rows() > 0)
        {
            return $query->result();
        } 

}
  

控制器

public function getDepartmentId($id)
{
    $this->load->model('Department_Model/Department_Model');

    $data['r'] = $this->Department_Model->getDepartmentIdForName($id,true);

    $data['r1'] = $this->Department_Model->getDepartmentImage($id,true);

     //redirect('admin/department' ,$data);
     $this->load->view('department' ,$data);

}
  

查看部门

<div class="col-sm-9">

        <?php $this->load->model('Department_Model/Department_Model');?>
        <?php foreach($r->result() as $deName):?>
            <h4>
                    <?php echo $deName->deptName?>
            </h4>


          <p> <?php echo $deName->deptInfo?></p>
          <!-- Small Facts -->

        <?php endforeach ;?>

  </div><!---col-sm-9-->

显示以下错误

  

未定义的变量:r   严重性:错误

     

消息:在非对象上调用成员函数result()

     

文件名:views / department.php

     

行号:35

3 个答案:

答案 0 :(得分:1)

在模型中更改此

if($query->num_rows() > 0)
{
    return $query->result_array();//here
} 

在视图中

<?php foreach($r as $deName):?>

答案 1 :(得分:0)

编辑你的控制器:

public function getDepartmentId($id)
{
    $this->load->model('Department_Model');

    $data['r'] = $this->Department_Model->getDepartmentIdForName($id);

    $data['r1'] = $this->Department_Model->getDepartmentImage($id);

     //redirect('admin/department' ,$data);
     $this->load->view('department' ,$data);

}

您无需在视图中再次加载模型。

    <?php foreach($r->result() as $deName):?>
        <h4>
                <?php echo $deName->deptName?>
        </h4>


      <p> <?php echo $deName->deptInfo?></p>
      <!-- Small Facts -->

    <?php endforeach ;?>

因为getDepartmentImage只有1个参数。

答案 2 :(得分:0)

在模型中,您将返回$query->result(),在视图中,您还会循环显示$r->result(),但$r是您从模型中返回的内容。所以你应该只在其中一个地方使用result()方法。只需从模型或视图中删除->result()即可。