February 13, 2018
Multiple database connection in codeigniter application
Generally we use one database for application but some times we need to use multiple database.
Codeigniter give the option to connect multiple database in application.
This tutorial gives idea about how you can connect and use multiple databases in CodeIgniter Application.
Normally, we have a default database group, like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$db['default']['hostname'] = "localhost"; $db['default']['username'] = "root"; $db['default']['password'] = ""; $db['default']['database'] = "database_name"; $db['default']['dbdriver'] = "mysql"; $db['default']['dbprefix'] = ""; $db['default']['pconnect'] = TRUE; $db['default']['db_debug'] = FALSE; $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = ""; $db['default']['char_set'] = "utf8"; $db['default']['dbcollat'] = "utf8_general_ci"; $db['default']['swap_pre'] = ""; $db['default']['autoinit'] = TRUE; $db['default']['stricton'] = FALSE; |
Notice that the login information and settings are provided in the array named $db[‘default’].
For multiple database connection, You can then add another database in a new array – let’s we name it as ‘seconddb‘.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$db['seconddb']['hostname'] = "localhost"; $db['seconddb']['username'] = "root"; $db['seconddb']['password'] = ""; $db['seconddb']['database'] = "second_database_name"; $db['seconddb']['dbdriver'] = "mysql"; $db['seconddb']['dbprefix'] = ""; $db['seconddb']['pconnect'] = TRUE; $db['seconddb']['db_debug'] = FALSE; $db['seconddb']['cache_on'] = FALSE; $db['seconddb']['cachedir'] = ""; $db['seconddb']['char_set'] = "utf8"; $db['seconddb']['dbcollat'] = "utf8_general_ci"; $db['seconddb']['swap_pre'] = ""; $db['seconddb']['autoinit'] = TRUE; $db['seconddb']['stricton'] = FALSE; |
while using multiple database connection in codeignter, you have to send the connection to another variabel that you can use in your model:
1 2 3 4 5 6 |
function getsourcecode_model() { $seconddb = $this->load->database('seconddb', TRUE); // the TRUE paramater tells CI that you'd like to return the database object. $query = $seconddb->select('first_name, last_name')->get('person'); var_dump($query); } |
For more information https://codeigniter.com/user_ guide/database/connecting.html
Hope this simple tutorial will help you get started with using codeigniter multiple database connection file upload functionality. If you are having problem or have a question, feel free to ask me about it. Happy coding 