Thursday, March 24, 2016

Joining two tables in codeigniter query

How to join two tables in codeigniter ?

Codeigniter table joining queries are used to join two database tables. Most of the php web developers know to join mysql database tables using core php but not by using codeigniter query builder. So, today we are going to discuss about joining two tables in codeigniter with examples.
How to join two tables in codeigniter
Codeigniter table join

Consider two database tables 
1)  students_account - To store students details.
2)  school_list - To store school details.

Table 1 : students_account
idstudent_nameschool_id
1Eshin3
2Jozer1
3Jacinth2
Table 2 : school_list
idschool_name
1StudentsBlog100
2W3schools100
3Sample School

Model

function test_model($student_id)
{
     $this->db->select('students_account.*,school_list.school_name');
     $this->db->from("students_account");
     $this->db->join('school_list', 'students_account.school_id = school_list.id', 'left');
     $this->db->where("students_account.id",$student_id);
     $query=$this->db->get();
          if($query->num_rows() > 0)
          {
          return $query->result();
          }
     return false;
}

Controller

public function test_controller() 
{
     $student_id = 2;
  
     $query = $this->model_name->test_model($student_id);  
          if($query)
          {
               echo "<pre>";
               print_r($query);
               echo "</pre>";
          }
          else
          {
               echo "problem in getting student's details";
          }
 }

Test by using above sample codes.. if you have any doubts or any mistakes in the codes given above, please let me know by commenting below.. Thank you, W3schools100 team

1 comment:

  1. Laravel Development Company, Get a free quote for laravel web development requirement from a leading Laravel Development Company. Discuss your web project with us to get large discounts...Contact us : +91-9806724185 or Contact@expresstechsoftwares.com

    ReplyDelete