CodeIgniter Forums
dynamic database connection - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: dynamic database connection (/showthread.php?tid=60632)



dynamic database connection - El Forum - 05-15-2014

[eluser]Unknown[/eluser]
Hi,
I am newbie in CI, i come from .NET, and want to use CI for my new project as a web GUI.

i have several databases, and i want to users able to manage their databases.
users data stores in USERS_TABLE and database login info stores in SERVERS_TABLE.

user must able to login and have access to related database (some controllers do logics ).
in fact i want to generate dynamic database connection for user (based on related db info) in some controllers.

how i can do this ?
please suggest me some idea.

tanks all.


dynamic database connection - El Forum - 05-15-2014

[eluser]noideawhattotypehere[/eluser]
http://ellislab.com/codeigniter/user-guide/database/connecting.html

Where and how you will store new configs - its up to you, just dont use persistent connection set to true as this may cause unexpected results


dynamic database connection - El Forum - 05-15-2014

[eluser]CroNiX[/eluser]
You don't have to store the config in a file which would defeat the point of a dynamic connection. Just create an array of the connection properties, like coming from your db for your specific user, and pass it to the load::database().

Code:
$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";

$db2 = $this->load->database($config, TRUE);

Now just use $db2 like you would $this->db and it will use the new connection instead of the default.
Code:
$db2->where('something', $id)->get('table')->result();

If you want it globally available, you should create a MY_Controller or library that is autoloaded, create a CI property to hold the connection, and load it there.