CodeIgniter Forums
Dynamic Database Connection - 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: Dynamic Database Connection (/thread-35275.html)



Dynamic Database Connection - El Forum - 10-25-2010

[eluser]Shobhit[/eluser]
Hi

I have 10 db and i want connect on the fly mean if i come from DB1 than my code automatically connect DB1 same with DB2 and DB3.


Dynamic Database Connection - El Forum - 10-25-2010

[eluser]WanWizard[/eluser]
Define all your databases in config/database.php
Code:
$db['db7']['username'] = ...
then load your database with
Code:
$this->load->database('db7');

How do you determine which database to connect to?


Dynamic Database Connection - El Forum - 10-25-2010

[eluser]Shobhit[/eluser]
Thanks for replying

But i want to know is there any way we can set Database name variable in controller or in model.
Suppose if my URL is http://myurl.com/index.php/welcome/method/AB
Than i want to connect AB database
if
http://myurl.com/index.php/welcome/method/XY
than XY connected.

Actually i don't no how many database i had, its totally dynamic process thats why i cant define all db name in config variable.


Dynamic Database Connection - El Forum - 10-25-2010

[eluser]WanWizard[/eluser]
How can it be totally dynamic?

Your database needs to be created, it has a username, password, server or IP, port, etc...

If someone creates a new database XY, you will not be able to connect to it unless you configure it in your application. And if you do, why not where it should be, which is the database config file. You can still use the database name and config index, and use it to load the required database config, as per my previous example.

Alternatively, you can always create the config array at runtime, in your controller. Check the user guide, "manually connecting...".


Dynamic Database Connection - El Forum - 10-25-2010

[eluser]Shobhit[/eluser]
Db name is only dynamic and other things are constant


Dynamic Database Connection - El Forum - 10-25-2010

[eluser]WanWizard[/eluser]
Use the "manual connecting" option as described in the user guide...