Search code examples
phpmysqlcodeigniter-3

How to display name instead of id if records are in one table?


I am using CodeIgniter. I have an employee table and records are

id |firstname | lastname | mobileno   | created_by
 2 |mnb       | nbgfv    | 1452145625 | 1
 3 |jhg       | uhgf     | 1452365478 | 2
 4 |poi       | ijuy     | 1458745632 | 2
 5 |tgf       | tgfd     | 1458745254 | 2
 6 |wer       | qwes     | 1523654512 | 2

Now My issue is in the column created_by. When I am displaying the record of any id value then I am getting the output like

    id |firstname | lastname | mobileno   | created_by
     3 |jhg       | uhgf     | 1452365478 | 2

But my expected output

id |firstname | lastname | mobileno   | created_by
 3 |jhg       | uhgf     | 1452365478 | mnb nbgfv

I have to display the name of created_by

I tried only this query.

   $get_single_emp_record = array('id' => 3);
   $this->db->where($get_single_emp_record);
   $query = $this->db->get('tbl_employee');
   $result = $query->row();
   if($result)
   {
   return $result;
   }
   else 
   {
   return 0;
   }

Solution

  • I have a hint (maybe this can give solution in your problem). Try query like this :

    SELECT 
    t1.id , t1.firstname , t1.lastname ,t1.mobileno, 
    CONCAT(t2.firstname ," ",t2.lastname ) AS createby 
    FROM tbl_employee AS t1 
    JOIN tbl_employee AS t2 ON t2.id = t1.created_by
    WHERE t1.id = '3'
    

    With above query you no need create temporary table or other additional tables. I Tested it. >>> http://sqlfiddle.com/#!9/e693cf/2/0

    Thanks