简体   繁体   中英

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 . How can i do that. Thanks in advance.

In the foreach you are reassigning the values to the same array. 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 .

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,

 $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);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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