遇到PHP错误严重性:通知消息:未定义变量:data文件名:profile / viewabout.php行号:79

时间:2017-09-12 04:30:46

标签: php codeigniter for-loop undefined codeigniter-3

控制器:我正在尝试从数据库中获取记录,但它在视图部分显示未定义的变量$ data。我不明白的问题是什么。

public function vabout(){
    if(!$this->session->userdata('logged_in')){
        redirect('register/login');
    }
    $this->load->model('profile_model');
    $data = $this->profile_model->viewprofile();

    $this->load->view('templates/pheader');
    $this->load->view('profile/viewabout',$data);
    $this->load->view('templates/pfooter');

}

型号:这是模型部分,模型中是否存在获取记录的问题?

public function viewprofile(){
    $data = $this->db->get('profile');
    return $data->row_array();
}

查看:错误:遇到php错误 $ data未定义

<?php
      foreach ($data as $row)
        { ?>
        <p><?php echo $row->id; ?></p>
        <p><?php echo $row->name; ?></p>
        <?php
      }
  ?>

2 个答案:

答案 0 :(得分:1)

您需要传递key名称$data不包含data作为键名称的数组,您传递key数组的每个data将变为图

public function vabout(){
                if(!$this->session->userdata('logged_in')){
                    redirect('register/login');
                }
                $this->load->model('profile_model');
                $data['data'] = $this->profile_model->viewprofile(); // add data as index

                $this->load->view('templates/pheader');
                $this->load->view('profile/viewabout',$data);
                $this->load->view('templates/pfooter');

            }

此外,您正在查看像对象一样的数据。所以在模型中不能将结果转换为数组

public function viewprofile(){
    $data = $this->db->get('profile');
    return $data->result();
}

答案 1 :(得分:1)

用以下代码替换您的代码:Controller

 public function vabout($id = NULL){
        if(!$this->session->userdata('logged_in')){
            redirect('register/login');
        }
        $this->load->model('profile_model');
        $data['data'] = $this->profile_model->viewprofile($id);

        $this->load->view('templates/pheader');
        $this->load->view('profile/viewabout',$data);
        $this->load->view('templates/pfooter');

    }

用这个替换模型。那是不是?

型号:

public function viewprofile($id = FALSE){
     if($id === FALSE){
        $query = $this->db->get('profile');
        return $query->result_array();
      }
         $query = $this->db->get_where('profile',array('id' => $id);
         return $query->row_array();
    }

查看:

<?php
              foreach ($data as $row)
                { ?>
                <p><?php echo $row['id']; ?></p>
                <p><?php echo $row['name']; ?></p>
                <?php
              }
          ?>