How to get value from two table using join in codeigniter?

Member

by orpha , in category: PHP Frameworks , 9 months ago

How to get value from two table using join in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 9 months ago

@orpha 

To get values from two tables using JOIN in CodeIgniter, you can follow these steps:

  1. Load the database library in CodeIgniter by configuring the database settings in the config/database.php file.
  2. Create a model for each of the tables you want to join. For example, if you have two tables named table1 and table2, create two models Table1_model.php and Table2_model.php.
  3. In the respective models, define a function to retrieve the desired values using the JOIN operation. For example, in Table1_model.php:
1
2
3
4
5
6
7
8
9
class Table1_model extends CI_Model {
    public function getJoinedData() {
        $this->db->select('*');
        $this->db->from('table1');
        $this->db->join('table2', 'table1.id = table2.table1_id', 'inner');
        $query = $this->db->get();
        return $query->result();
    }
}


In this example, the table1.id column is joined with table2.table1_id using the inner join. Adjust the column names and join type based on your table structure.

  1. In your controller, load the corresponding models and call the defined functions to fetch the joined data.
1
2
3
4
5
6
7
class Your_controller extends CI_Controller {
    public function index() {
        $this->load->model('Table1_model');
        $joinedData = $this->Table1_model->getJoinedData();
        // Use the $joinedData as desired
    }
}


Now you can use the $joinedData obtained from the JOIN operation as per your requirements in the controller or pass it to the view to display the data.