Codeigniter,显示数据库的结果

时间:2013-05-05 03:03:54

标签: codeigniter

我是CI的新手,我已经花了好几个小时没有成功,请帮忙!我试图通过从数据库中检索信息并在视图中显示它(使用USERID)来生成用户配置文件。我得到一个未定义的变量错误,并尝试从非对象错误中获取属性。这是我的代码:

型号:

 public function my_data()
{
  $userid = $this->session->userdata('userid');

  $data = array();
  $this->db->select('*');
  $this->db->from('user_profile');
  $this->db->where('userid', $userid);
  $query = $this->db->get();

  return $query->result();
  }

控制器:

    public function profile()
{

         $data['query'] = $this->user_model->my_data();



         $this->load->view('header_loggedin');
        $this->load->view('sidebar_left');
        $this->load->view('user/user_profile', $user);
        $this->load->view('footer');
}

查看:

<div class="control-group">
 <i class="icon-user"></i>
            Name: <?php echo $row->name; ?>     
</div>
    <div class="control-group">
 <i class="icon-home"></i>
            Location: <?php echo $data->location;?> 
</div>
        <div class="control-group">
 <i class="icon-briefcase"></i>
            Occupation: <?php echo $data->occupation;?> 
</div>

非常感谢,我觉得我已经尝试了一切!

2 个答案:

答案 0 :(得分:0)

嗨,作为CI的新手,你会遇到一些问题,但后来你会喜欢这里有一些你做错的简单事情

模型

public function my_data()
{
  $userid = $this->session->userdata('userid');

  $data = array();
  $this->db->select('*');
  $this->db->from('user_profile');
  $this->db->where('userid', $userid);
  $query = $this->db->get();

  //this will return multiple rows or object of arrays
  //return $query->result();
  // you need to send only single row
    return $query->row();
  }

控制器

public function profile()
{
         // in data array key name should be same which you will pass to view    
         $data['row'] = $this->user_model->my_data();



         $this->load->view('header_loggedin');
        $this->load->view('sidebar_left');
        $this->load->view('user/user_profile', $data);
        $this->load->view('footer');
}

查看

<div class="control-group">
 <i class="icon-user"></i>
            Name: <?php echo $row->name; ?>     
</div>
    <div class="control-group">
 <i class="icon-home"></i>
            Location: <?php echo $row->location;?> 
</div>
        <div class="control-group">
 <i class="icon-briefcase"></i>
            Occupation: <?php echo $row->occupation;?> 
</div>

如需了解更多信息,请阅读CI用户指南,了解那里有很多内容CI user guide

答案 1 :(得分:0)

此处将 $ user更改为$ data

public function profile()
{

         $data['result'] = $this->user_model->my_data();



         $this->load->view('header_loggedin');
        $this->load->view('sidebar_left');
        $this->load->view('user/user_profile', $data);
        $this->load->view('footer');
}

然后,如果您的查询只返回一行,则可以使用

return $query->row_array();

而不是

return $query->result();

在视图中,您现在可以使用

Name: <?php echo $result['name']; ?>
Location: <?php echo $result['location'];?> 
Occupation: <?php echo $result['occupation'];?>