Welcome Guest, Not a member yet? Register   Sign In
Dynamically connecting to multiple databases - but only 1 at a time
#1

[eluser]Unknown[/eluser]
I have been reading a lot of posts on the forums here, but none quite match what I am specifically trying to do. I inherited a system that has one SQL host but over 10 databases on that host, and I need to be able to connect to the database that the user specifies. This database can change at any time, based on what the user needs, and the databases have similar schema (same tables, etc).

Because the database can change at any time, I don't think that my config/database file can--or even should-- have 10+ entries for each database. In addition, I would like to be able to do
Code:
$this->db->select()
(or similar) in each of my models and have it work no matter the database that is connected.

I've studied this page http://ellislab.com/codeigniter/user-gui...cting.html but it doesn't quite seem what I need to do: I don't need to connect to more than one at a time, I just need to dynamically change which one I am connected to and have my models query the database without code modification.

Can anyone guide me? Thanks.
#2

[eluser]CroNiX[/eluser]
Do all of your databases use the same user credentials? If so, you can just:

Code:
$this->db->query('USE other_database');
now any further queries will use other_database.

Code:
$this->db->query('USE original_database');
now any further queries will use original_database.

I've tested the above and it works for the same user/credentials.

If they don't use the same user credentials/permissions, you'd probably have to (untested):
Code:
$this->db->close();  //terminate original connection
$this->load->database($config_settings_for_other_user);  //reload using different credentials
#3

[eluser]Unknown[/eluser]
Thanks, I'll look at this and get back to you tomorrow!

Edit: This led me on the right track. It still seems more complicated than it should be (if you want to stick to DRY principles) but I'll get it to work. Thanks.

Edit 2: I'm trying to mark your response as the answer, but it isn't working (I tried two different computers). Thanks though!




Theme © iAndrew 2016 - Forum software by © MyBB