Last Updated: January 23, 2019
·
24.5K
· desertlynx

Codeigniter: loading up multiple databases

Codeigniter's documentation does offer some insight into how to connect to multiple databases, but I didn't find it satisfactory. It suggests that by passing a second parameter
to the loader allows it to return an object which may be then queried like the normal $this->db->query();. Thus:

$DB1 = $this->load->database('config1', TRUE); 
$DB2 = $this->load->database('config2', TRUE); 

$DB1->query();

For my purposes at least this wasn't satisfactory because:

  • I had an existing codebase using the more conventional $this->db->query() which would then have to be refactored.
  • It gave the ability to load up the database as needed, but not all the time as was the case with the previously autoloaded config.
  • It didn't work, the databases loading order affected one another and conflicted if called within the same method.

Solution:

Turn persistent connections off when using multiple connections fixes the problem of connection conflicts:

$db['default']['pconnect'] = FALSE;

Although beware this will likely incur a performance penalty as the connection now needs to be reestablished to the database at every connection

My solution to load up the databases more permanently was to create a custom loader library which handles this and places the connections in the traditional CI object. In my case, I added this library to /applications/config/autoload.php in the appropriate section:

/**
  * A simple class which handles loading multiple-databases in codeigniter
  */

 class DatabaseLoader {

         public function __construct() {
                 $this->load();
         }

         /**
          * Load the databases and ignore the old ordinary CI loader which only allows one
          */
         public function load() {
                 $CI =& get_instance();

                 $CI->db = $CI->load->database('default', TRUE);
                 $CI->db2 = $CI->load->database('db2', TRUE);
         }

5 Responses
Add your response

Thank you very much. I spent hours looking for this.

over 1 year ago ·

Happy to be of help :)

over 1 year ago ·

ahh...finally its working.......thanks bro... :)

over 1 year ago ·

sorry I still do not understand , would you explain in more detail. many thanks :)

over 1 year ago ·

If you have created multiple database connection, you have to close the connection to one database and then connection to another database. You can follow this guide on Codeigniter multiple database connection to know how to do it.

over 1 year ago ·