Problem connecting multiple CodeIgniter databases

5

I have an application where it connects to multiple databases, initially I use the database settings database.php .

When I connect to another database, it still loads the settings from the database.php file, so I make the following connection:

$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = "";
$config['char_set'] = "utf8";
$config['dbcollat'] = "utf8_general_ci";

$this->load->database($config);
    
asked by anonymous 02.03.2015 / 19:41

1 answer

5

You should change the access settings for your main database in your application / configdatabase.php file to:

$config['default']['hostname'] = "localhost";
$config['default']['username'] = "myusername";
$config['default']['password'] = "mypassword";
$config['default']['database'] = "mydatabase";
$config['default']['dbdriver'] = "mysql";
$config['default']['dbprefix'] = "";
$config['default']['pconnect'] = FALSE;
$config['default']['db_debug'] = TRUE;
$config['default']['cache_on'] = FALSE;
$config['default']['cachedir'] = "";
$config['default']['char_set'] = "utf8";
$config['default']['dbcollat'] = "utf8_general_ci";

Then, a few lines above, in the same file, define the main database group:

$active_group = 'default';

In the same file, for each other database that you need to connect to, create a new group of settings by changing the group ID and connection settings:

$config['secundario']['hostname'] = "localhost";
$config['secundario']['username'] = "myusername";
$config['secundario']['password'] = "mypassword";
$config['secundario']['database'] = "mydatabase";
$config['secundario']['dbdriver'] = "mysql";
$config['secundario']['dbprefix'] = "";
$config['secundario']['pconnect'] = FALSE;
$config['secundario']['db_debug'] = TRUE;
$config['secundario']['cache_on'] = FALSE;
$config['secundario']['cachedir'] = "";
$config['secundario']['char_set'] = "utf8";
$config['secundario']['dbcollat'] = "utf8_general_ci";

In your methods when calling $ this-> db you will be acting on the main database. Whenever you want to act on another database, simply load it dynamically, as follows:

$bd_secundario = $this->load->database('secundario', TRUE);

After loading, you can operate on it in the same way as $this->db , such as

$bd_secundario->query('SELECT * FROM world').
    
15.04.2015 / 17:26