简体   繁体   English

在codeigniter中获取id=$id的数据库中的所有行

[英]Get all rows form database where id=$id in codeigniter

Here is my code这是我的代码

 $this -> db -> select('*');
        $this -> db -> from('events');
        $this -> db -> where('user_id',$session_data['id']);


        $query = $this -> db -> get();

        $result = $query->result();

        if($result)
        {

            $events_array = array();
            foreach($result as $row)
            {
                $events_array = array(
                    'id' => $row->id,
                    'title' => $row->title,
                    'ev_img_name' => $row->ev_img_name,

                );

                $this->session->set_userdata('events',$events_array);
            }
            $session_data = $this->session->userdata('events');
            $id = $this->session->userdata('id');
            $data['id'] = $id;
            $data['id'] = $session_data['id'];
            $title = $this->session->userdata('title');
            $data['title'] = $title;
            $data['title'] = $session_data['title'];
            $ev_img_name = $this->session->userdata('ev_img_name');
            $data['ev_img_name'] = $ev_img_name;
            $data['ev_img_name'] = $session_data['ev_img_name'];

It gets only the first row of the table, but i need to get all rows with same user_id .它只获取表的第一行,但我需要获取具有相同 user_id 的所有行。 How can i do that.我怎样才能做到这一点。 Thanks in advance.提前致谢。

In the foreach you are reassigning the values to the same array.在 foreach 中,您将值重新分配给同一个数组。 Try using尝试使用

 $events_array = array();
 foreach($result as $row)
 {
      $events_array[] = array(
          'id' => $row->id,
          'title' => $row->title,
          'ev_img_name' => $row->ev_img_name,
      );

}
$this->session->set_userdata('events',$events_array);

This way you will have all the rows from the returned result in the $events_array .这样,您将拥有$events_array返回结果的所有行。

Now in your view you can do this现在在你看来你可以这样做

<?php foreach($events_array as $event) { ?>
   <div class="event">
      Title: <?= $event['title'] ?>
      Image: <br>
      <img src="<?= $event['ev_img_name'] ?>">
   </div>
<?php } ?>

Try This Code, you can directly get the data whatever you want(number of fields) in array format from codeigniter sql query and than set that array directly to session as event like below,试试这个代码,你可以直接从 codeigniter sql 查询中以数组格式获取任何你想要的数据(字段数),然后将该数组直接设置为会话作为事件,如下所示,

 $this->db->select('id,title,ev_img_name');
 $this->db->from('events');
 $this->db->where('user_id',$session_data['id']);

 $result = $this->db->get()->result_array();

 if(count($result)>0){
      $this->session->set_userdata('events',$result);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM