How to connect more than two databases in codeigniter?

by wilmer.lemke , in category: PHP CMS , a year ago

How to connect more than two databases in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year ago

@wilmer.lemke 

To connect more than two databases in CodeIgniter, you can follow these steps:

  1. Configure the database connections in the config/database.php file. You can add multiple database configurations by setting up an array of database connection settings as shown below:
 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
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'database1',
    '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
);

$db['database2'] = array(
    // Configuration settings for second database
);

$db['database3'] = array(
    // Configuration settings for third database
);


  1. Load the database by specifying the database group name in the load->database() method like this:
1
2
3
$DB1 = $this->load->database('default', TRUE);
$DB2 = $this->load->database('database2', TRUE);
$DB3 = $this->load->database('database3', TRUE);


  1. You can now use these variables $DB1, $DB2, and $DB3 to perform database operations with the corresponding databases.
1
2
3
$query1 = $DB1->query('SELECT * FROM table1');
$query2 = $DB2->query('SELECT * FROM table2');
$query3 = $DB3->query('SELECT * FROM table3');


By following these steps, you can successfully connect and perform operations on more than two databases in CodeIgniter.

Related Threads:

How to join between two databases in codeigniter?
How to display two counts using oracle databases?
How to connect ffmpeg with codeigniter?
How to connect to postgresql in codeigniter?
How to connect database in Codeigniter?
How to connect with the mongodb through codeigniter?