Welcome Guest, Not a member yet? Register   Sign In
Runtime database connection details setup
#1

[eluser]Unknown[/eluser]
Hello,
How can I access the database connect variables in one of my controllers? Something like /config/database.php, the reason for this is I must access multiple databases and don't know the connection details until runtime.
I could write a simple static php that reads the details, outputs in the /config/database.php and starts the CI application but that's really ugly coding, I'd like something like:
-no db autoconnect in config.
-controller1 reads the connection details: host, db, user, pass and stores in session
-controller2,3,4... reads from session and does something like:
$this->db->config->host= $this->db->config->user= etc and then $this->db->connect();

I don't know the number of DBs involved so multiple profiles in database.php is not an option.

Thank you!
#2

[eluser]theprodigy[/eluser]
According to the database section of the user_guide
Quote:To connect manually to a desired database you can pass an array of values:
$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);

Just fill the config array with the necessary values at runtime, then pass it into the load->database call.

To connect to multiple databases, just set some variables equal to the load->database call, and pass in TRUE for the second parameter (it's listed in the same section of the user guide)
Quote:If you need to connect to more than one database simultaneously you can do so as follows:
$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Use these two in techniques together, and come up with something like:
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";

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

$config['username'] = "myusername_2";
$config['password'] = "mypassword_2";
$config['database'] = "mydatabase_2";

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

If you need to be connected to both databases at the same time, make sure to leave pconnect set to false, otherwise you may run into issues.




Theme © iAndrew 2016 - Forum software by © MyBB