CodeIgniter Forums

Full Version: Dynamic database selection
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]cpass78[/eluser]
Hello,

I have a need to connect to many databases from a form to check if certain tables exist. There could potentially be hundreds of DB's and the names are not known yet. I'd need to connect to one based on
Code:
$this->input->post();
value.

Is there any way to do this without messing with the database.php config file? My username password and host would all remain the same just the db would need to change.

I did try
Code:
$config['database'] = "study_".$this->studycode;
        if ($this->load->database($config)){
            echo "true";
        }else{
            echo "false";
        }
and it always returns false, but the post vale is correct.

Thank you!

El Forum

[eluser]WanWizard[/eluser]
You can load the database (this way) only once, after which it is assigned to $this->db. If you try to load another one, it detects it's already loaded, and returns false.

Secondly, if you try to load a database with a manual config, you need to pass all information in the array. If you want to reuse the default config, you have to load that first.

Try
Code:
// load the database config
include(APPPATH.'config/database'.EXT);

// get the default config
$config = $db['default'];

// override the database name
$config['database'] = "study_".$this->studycode;

// do not auto initialize the connection
$config['autoinit'] = FALSE;

// load the database driver
$db = $this->load->database($config, TRUE);

// and see if we can initialize it
if ( $db->initialize() ) {
    echo "true";
}
else
{
    echo "false";
}

El Forum

[eluser]cpass78[/eluser]
Thanks for the response, That looks like it will work but i just kept it simple with
Code:
$select = @mysql_select_db("study_".$this->studycode);
        if ($select){
            echo "true";
        }else{
            echo "false";
        }

May or may not be a "proper way way to do it but it works for the time being.

Thank you again!

El Forum

[eluser]cpass78[/eluser]
Actually i chose to implement your method and it works like a charm, solved it for me.

Thanks a million