First Off A Word of Warning
It should go noted that this probably is not a recommended best idea, unless you limit the users allowed database names or do not allow them to select it themselves.
If the first scenario is a must, please sanitize the data, and if you know its a defined list of db names.. provide them a list and do validation against the list.
That being said:
Here is your described code. I do this in my controller. And reference $db2->
in my model.
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = $customUserDatabase;
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$DB2 = $this->load->database($config);
$q = $DB2->where('id', 13)->get('tablename');
if( $q->num_rows() > 0 ){
return $q->result();
}else{
return false;
}
http://codeigniter.com/user_guide/database/connecting.html
Reference the part about connecting to multiple databases...
Connecting to Multiple Databases
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);
Note: Change the words
"group_one" and "group_two" to the specific group names you are
connecting to (or you can pass the connection values as indicated
above).
By setting the second parameter to TRUE (boolean) the function will
return the database object.
When you connect this way, you will use your object name to issue
commands rather than the syntax used throughout this guide. In other
words, rather than issuing commands with:
$this->db->query(); $this->db->result(); etc...
You will instead use:
$DB1->query(); $DB1->result(); etc...
Live Working Code Example.
I put a snippet of my Controller/Model using this exact same feature. I had a need to connect to multiple databases using the same credentials/configs across multiple db's.. as a result i was able to use $this->db->
to get configs.
You can see the gist of it here: https://gist.github.com/08a4f45da1ff7e177425