简体   繁体   中英

join table technique using codeigniter

Guys on my database i have three tables containing data as shown on a link below. On tables class and subjects , ssid and csid are foreign key from members .

I joining tables using left join as shown in model code shown below. when i echo first_name, surname and class_name for John claudius it appears three times while for Alex massawe it appear only once. but if i add information for Alex massawe result will displayed out as many times as information for Alex massawe that are within subjects. I need your help so that information given out will not be repeated if add information on tables subjects for a person whose name already in tables members.

Tables within database

my tables

members

sid first_name surname
a001 alex massawe
a002 John claudius

class

id csid class_name
01 a001 baby_class
02 a002 Class_one

subjects

id ssid subject_name
01 a002 Mathematics
02 a002 literature
03 a002 Communication skills

codes



Models:


function get_particular($sid){
$this->db->select('*');
$this->db->from('members m');
$this->db->join('subjects s', 'm.sid=s.ssid', 'left');
$this->db->join('class c', 'm.sid=c.csid', 'left');
$this->db->where('m.sid', $sid);
$query = $this->db->get();
return $query->result_array();
}

Controller:

function particular($sid){
$sid=$this->uri->segment(3);
$this->load->model('names');

$this->data["names"]=$this->names_rank->get_particular($sid);
$this->load->view("view/details", $this->data);
}

view:

foreach($names as $name) {

echo $name['sid'].' '. $name['first_name'].' '. $name['surname'].' '.$name['class_name'];
}

What if you remove the loop - Changing your view

From

foreach($names as $name) {

echo $name['sid'].' '. $name['first_name'].' '. $name['surname'].' '.$name['class_name'];
}

To

echo $name['sid'].' '. $name['first_name'].' '. $name['surname'].' '.$name['class_name'];

or if you need the loop, then it should loop for each member and echo name. ie foreach $member echo $names

Details from tables members (first_name and surname) and class (class_name) are shown in view. So remove the left join to subjects table from query. this join is the reason for repeated records if there are more than one record for same member

$this->db->select('*');
$this->db->from('members m');
$this->db->join('class c', 'm.sid=c.csid', 'left');
$this->db->where('m.sid', $sid);
$query = $this->db->get();
return $query->result_array();

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