CodeIgniter Forums
Switching database config for model not working: $this->load->database('name') - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Switching database config for model not working: $this->load->database('name') (/thread-43754.html)



Switching database config for model not working: $this->load->database('name') - El Forum - 07-21-2011

[eluser]fdgsuhofdshjdfgh[/eluser]
Hi,

I have 2 database configs defined in config/database.php:

Code:
$active_group = 'primary';
$active_record = TRUE;

$db['primary']['hostname'] = 'localhost';
...
$db['secondary']['hostname'] = 'localhost';
...

I have primary set to my default. I have a model that needs to use the secondary database so I do the following, as instructed by the documentation:

Code:
function list_clients($company)
{
    $this->load->database('secondary');
    $company_query = $this->db->query('SELECT * FROM secondary_table');
}

but this doesn't work, it tries to connect to the primary database.

I have tested if it's a configuration error by switching the active_group variable to "secondary" and then it connects fine and works as expected. So the problem is for some reason:

Code:
$this->load->database('secondary');

is being ignored. What am I doing wrong? Any gotcha I'm missing? Tried on both Windows and Linux. PHP 5.3.4


Switching database config for model not working: $this->load->database('name') - El Forum - 07-22-2011

[eluser]mejlo[/eluser]
HI,
try:
Code:
$db = $this->load->database('secondary', TRUE);
$company_query = $db->query('SELECT * FROM secondary_table');



Switching database config for model not working: $this->load->database('name') - El Forum - 07-24-2011

[eluser]Unknown[/eluser]
I found your question because I was having the same problem.
I found the issue for me to be because I was auto loading the database library, which creates a database connection to your default database connection every time you load a page. You can turn this off in the config/autoload.php file
Change
Code:
$autoload['libraries']('database');
to
Code:
$autoload['libraries']();