In this tutorial you will learn about the Multiple database connection in codeigniter and its application with practical example.
In this Multiple database connection in codeigniter tutorial I will show you how to connect multiple database in codeigniter single application. In this tutorial you will learn to use multiple database connection in codeigniter. You will also learn how to connect multiple database in single codeigniter application.
Multiple database connection in codeigniter
In this tutorial I will share following example to connect or use multiple database in codeigniter application. In this example we will be defining two arrays in application/config/database.php file as following –
application/config/database.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); $active_group = 'default'; $query_builder = TRUE; // codeigniter provide default code $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => '', 'password' => '', 'database' => '', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE ); // second connectivity of database $db['second_db'] = array( 'dsn' => '', 'hostname' => 'here add second database of hostname', 'username' => 'here add second database of username', 'password' => 'here add second database of password', 'database' => 'here add second database of database name', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE ); ?> |
Now we can access different database connection as following –
1 2 3 4 5 6 7 |
//access default database $this->load->database(); $query = $this->db->query('select * from register'); //access the second database $second_db= $this->load->database('second_db', TRUE); $query = $second_db->get('select * from register2'); |