In CodeIgniter how do I load a database from a separate file, not the default config\database.php ?
Lets say that under libraries I have a folder named db_configs. Inside each database, details will be stored in separate file, ex. DB_01.php, DB_02.php,etc.
Thanks,
It is much easier to use the functionality built in to CI where multiple database connections can be defined in one file. To do otherwise is to reinvent the wheel.
Any given connection set (as defined in database.php) can be selected when you load the database. For instance, given DB_01 and DB_02 you would load them with
$this->load->database('DB_01');
or
$this->load->database('DB_02');
If you need both at once you can do this
$db1 = $this->load->database('DB_01', TRUE);
$db2 = $this->load->database('DB_02', TRUE);
But if you must have separate files there are a couple different approaches. Perhaps the easiest is to use helpers
application/helpers/db2_helper.php
function db2Config()
{
return array(
'dsn' => '',
'hostname' => 'localhost',
... etc.
);
}
In some controller
$this->load->helper('db2');
$db2_settings = db2Config();
$this->load->database($db2_settings);
It could also be done using the Config class like this.
application/config/db2.php
<?php
$config['dsn'] = '';
$config['hostname'] = 'localhost';
$config['username'] = 'IAmAUser';
$config['password'] = 'mypassword';
$config['database'] = 'theDB';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = TRUE;
...
In some controller
$this->config->load('db2', TRUE);
$db2_config = $this->config->item('db2');
$this->load->database($db2_config);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With