在视图codeigniter中显示查询

在视图codeigniter中显示查询,codeigniter,Codeigniter,假设来自我的控制器的查询是$query。 除了使用这种代码,如何显示数据 foreach($query as $row){ echo $row->student_id; } 除此之外的任何查询都只有一行 有什么方法可以像这样访问返回的数组吗 $query['student_id']; 假设您的表具有以下字段 student_id and student_name 让您的模型或控制器只返回一行 function get_first_student() { $query = t

假设来自我的控制器的查询是$query。
除了使用这种代码,如何显示数据

foreach($query as $row){
echo $row->student_id;
}
除此之外的任何查询都只有一行
有什么方法可以像这样访问返回的数组吗

$query['student_id'];

假设您的表具有以下字段

student_id and student_name
让您的模型或控制器只返回一行

function get_first_student() {

    $query = this->db->select('*')->from('student')-where('student_id','1')->limit(1);
    $data['stuff'] =  $query->row_array(); // or $query->row() which returns an object
    $this->load->view('whatever',$data)

}
那么在你看来,

<p>student name: <?= $stuff['student_name'] ?> </p>
<p>student id: <?= $stuff['student_id'] ?> </p>
学生姓名:

学生证:


实际上,
$query->row()
只获取第一行

因此,不必循环遍历结果,您只需执行以下操作:

$student_id = $query->row()->student_id; // (untested)


假设查询总是返回一行。

假设您正在显示用户的配置文件。最好将所有数据库查询存储在模型中。我用这个:

控制器:

$this->load->model('Profile');
$data['row'] = $this->Profile_model->profile_read(); //get profile data
$this->load->view('profile_view', $data); //load data to view
型号:

function profile_read()
{
        $this->db->where('user_id', $user_id);
        $query = $this->db->get('user_profiles'); //get all data from user_profiles table that belong to the respective user
        return $query->row(); //return the data    
}
在模型中,您可以拥有所有其他数据库功能(创建、删除、更新)

视图:


最后,在视图中,您可以回显表中属于用户的任何行。

另一种选择是将数据存储在会话中,该会话可以在站点上的任何位置访问,而无需每次查询。一些最适合存储在会话中的数据是用户名或用户id。
function profile_read()
{
        $this->db->where('user_id', $user_id);
        $query = $this->db->get('user_profiles'); //get all data from user_profiles table that belong to the respective user
        return $query->row(); //return the data    
}
<?php echo $row->name; ?>
<?php echo $row->email; ?>
<?php echo $row->about; ?>
etc