Vinie
Vinie

Reputation: 2993

How to join table to show multiple data?

I am new in Codeigniter. I have a problem I have two tables Set and Subject

Set has column Id, Set_name and Subject has column id, subject_name,set_id

I want to show dara as below image

I have to add data like below image

i used following code

controller

$where=array('user_id'=>$this->session->userdata['logged_in']['id']); $val=array('id','set_name','desc','status'); $data['set']=$this->login->get_where2($val,$where,'q_set'); $select=array('id','name','set_id'); $data['sub']=$this->login->get_some($select,'subject'); $data['msg']=$this->session->flashdata('msg'); $this->load->view('admin/header'); $this->load->view('i_user/setlist',$data); $this->load->view('admin/sidebar');

view

<tbody> <?php foreach($set as $setdata){?> <tr> <td class="center"><?php echo $setdata->set_name;?></td> <td class="center"><?php foreach($sub as $subdata){ if($subdata->set_id==$setdata->id){?><span class='subject'><?php echo $subdata->name;?></span><?php }}?><a href="<?php echo base_url()?>user/subject" style="float:right;">Add Subject</a></td> <td class="center"><?php if($setdata->status==1){echo 'Published';}else{echo 'Unpublished';}?></td> </tr> <?php }?> </tbody>

This code is working well, but i think there is some unnecessary loops are running to show subject name. Is there any other way to do this? If yes then please suggest. I really appreciate your help.

Upvotes: 0

Views: 75

Answers (1)

shan22
shan22

Reputation: 131

Set has column *Id, Set_name* and Subject has column *id, subject_name,set_id*`

$this->db->select('Set.Set_name,Subject.subject_name');
$this->db->from('Set');
$this->db->join('Subject','Subject.set_id=Set.id','left');
$query = $this->db->get();
return $query->run();

Try this.It's a left join between both tables.

Upvotes: 1

Related Questions