0

There are two tables 'student' and 'parent'. both tables have 'f_name' and 'l_name' columns. I used left join for those two tables.

I want to display data from those two tables. However, when I use the following code I get 'parent name' in the column where student name is supposed to be shown. I get that it happens because both tables have 'f_name' and 'l_name' columns. but How do you fix this?

Controller

function index()
{
    $this->load->model('Tableview_model');


    $student_data= $this->Tableview_model->fetch_data();
    $data["student_data"]  =  $student_data;



    $this->load->view('register_students', $data);


}

model

function fetch_data()
{

        $this->db->select('s.student_code, s.f_name, s.l_name, s.tel, p.f_name, p.l_name');
        $this->db->from('student as s');
        $this->db->join('parent as p','s.p_id=p.p_id','Left');
        $query=$this->db->get();

    if($query->num_rows() > 0) 
    {
        return $query->result();


    }else{
        return false;
    }

}

view

        <?php
        foreach ($student_data AS $row) {
            ?>
            <tr>
                <td><?php echo $row->student_code; ?></td>
                <td><?php echo $row->f_name; ?> <?php echo $row->l_name; ?></td> //I'm supposed to get student first name and last name here
                <td><?php echo $row->tel; ?></td>
                <td><?php echo $row->tel; ?></td>
                <?php
            if(isset($row->f_name) && isset($row->l_name)){ // using isset() because of LEFT JOIN
                ?>
                <td><?php echo $row->f_name; ?> <?php echo $row->l_name; ?></td> //I'm supposed to get parent first name and last name here


                <?php
                    }
                }
            ?>

output

enter image description here

2
  • s.f_name as studentName, s.l_name as studentSurname Commented Feb 11, 2019 at 14:22
  • Ohh thank you so much its working :D Commented Feb 11, 2019 at 14:32

1 Answer 1

2

You can make alias of field name as below:

    $this->db->select('s.student_code, s.f_name, s.l_name, s.tel, p.f_name as pf_name, p.l_name as pl_name');
    $this->db->from('student as s');
    $this->db->join('parent as p','s.p_id=p.p_id','Left');
    $query=$this->db->get();

And can use pf_name and pl_name in your view. Hope it helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.