I'd like to dynamically switch from a database to another one, whose name has been dynamically given by the user.
Here are some significative fragments of my code :
//database.php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'firstbase',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
$db['newbase'] = $db['default'];
As you can see, 'newbase' is a simple copy of the default config
//Install_model Model
echo "<BR>Active db :".$this->db->database;
$this->createDB($database);
$this->db->close();
//now $database is created
//load the 'newbase' group and assign it to $this->newDb
$this->newDb = $this->load->database('newbase', TRUE);
//this will output 'firstbase'
echo "<BR>so far, the active db is :".$this->newDb->database;
$this->newDb->database=$database;
//now this will output the $database string
echo "<BR>and now the active db is :".$this->newDb->database;
Now, I want dbforge to be used on this new database.
$linkfields = array(
'table_id' => array(
'type' => 'VARCHAR',
'constraint' => '15'
),
'something' => array(
'type' => 'VARCHAR',
'constraint' => '15',
'unique' => TRUE,
),
);
//according to the manual, we "give" our new DB to dbforge
$this->myforge = $this->load->dbforge($this->newDb, TRUE);
$this->myforge->add_field($linkfields);
$this->myforge->add_key('table_id', TRUE);
$this->myforge->create_table('Link');
This works but...the table is created in 'firstbase' ! And though the database that is loaded is the second one. How can I solve this ?
EDIT #1
Apparently, $this->newDb->database=$database;
is not persistent. If the connexion is closed, then re-opened, $this->newDb->database
has the value it is initially given in the database config file. But this doesn't explain why I get those results, as I don't close the connexion.
If I add this to the config file : $db['newbase']['database'] = '';
then I get a #1046 error : No database selected. This confirms the fact that $this->newDb->database
is not used by dbforge, which prefers to use the hard-coded value instead.