Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter Multiple database use without changing existing code for first database

I have successfully configured a second database with codeigniter and was able to create a table. The problem is now that every previously existing lines of code that was using $this->db now uses the second database so naturally it pops an error. Let me explain with a bit more details:

I use the migration library of codeigniter and in a new migration, I create the database with dbforge like so $this->dbforge->create_database('website_store'). So far so good, then I connect to this database using $DB2 = $this->load->database('store', TRUE); and create a table. All is good here as well.

Then the migration ends and codeigniter tries to update the migration table to push the latest version, but looks into the store database instead of the default database, so it pops this error:

Table 'website_store.migrations' doesn't exist
UPDATE `migrations` SET `version` = 45

Hopefully someone knows about using multiple database and the migration library. By the way, in the database.php file, it is set to use the default database: $active_group = "default";, not the store database so it should work. It looks like the migration library sees that there is already a database loaded, feels lazy and uses that one instead.

NOTE: Looks like these guys had similar problems that they fixed by setting 'pconnect' to 'false', but it would be nice to keep a connection to both database:

Convenient Way to Load Multiple Databases in Code Igniter

Error Using Multiple Database In CodeIgniter

like image 725
Bobs Avatar asked Nov 12 '22 01:11

Bobs


1 Answers

In CI i have dealt with multiple databases using:

function readFromOtherDB(){
    $config = array(
        'hostname' => "XXX",
        'username' => "XXX",
        'password' => "XXX",
        'database' => "XXX",
        'dbdriver' => "mysql",
        'dbprefix' => "",
        'pconnect' => FALSE,
        'db_debug' => TRUE,
        'cache_on' => FALSE,
        'cachedir' => "",
        'char_set' => "utf8",
        'dbcollat' => "utf8_general_ci"
    );

    $otherDb = $this->ci->load->database($config, true);

    $query = $otherDb->get_where('users', array('email' => $_email));

    $otherDb->close();
}
like image 86
James Avatar answered Nov 15 '22 07:11

James