How to join between two databases in codeigniter?

Member

by addison , in category: PHP Frameworks , a month ago

How to join between two databases in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , a month ago

@addison 

To join between two databases in CodeIgniter, you need to first establish connections to both databases in your database configuration file. Then, you can use the following steps to join tables from these two databases:

  1. Load the second database connection in your controller or model:
1
2
// Load second database connection
$second_db = $this->load->database('second_db', TRUE);


  1. Write your SQL query to join between the tables in the two databases:
1
2
$query = $this->db->query("SELECT * FROM database1.table1 t1
                            JOIN second_db.table2 t2 ON t1.id = t2.id");


  1. Fetch the results of the query:
1
$results = $query->result();


You can also use the CodeIgniter Query Builder class to join tables from multiple databases. Here is an example using the Query Builder class:

1
2
3
4
5
$this->db->select('*');
$this->db->from('database1.table1 t1');
$this->db->join('second_db.table2 t2', 't1.id = t2.id', 'inner');
$query = $this->db->get();
$results = $query->result();


By following these steps, you can successfully join tables from two different databases in CodeIgniter.