2016-08-12 95 views
0

我想动态地从数据库切换到另一个,其名称已由用户动态给出。DB伪造,代码点火器和动态数据库选择

这里是我的代码一些有意义的片段:

//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']; 

正如你所看到的,“newbase”是默认配置的简单复制现在

//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; 

,我想dbforge是用于这个新的数据库。

$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'); 

这种方法可行,但...表格是在'firstbase'中创建的!尽管加载的数据库是第二个。我该如何解决这个问题?

编辑#1

显然,$this->newDb->database=$database;是不持久的。如果连接关闭,然后重新打开,$this->newDb->database具有最初在数据库配置文件中给出的值。但是这并不能解释为什么我会得到这些结果,因为我没有关闭这个关系。

如果我将此添加到配置文件:$db['newbase']['database'] = '';然后我得到#1046错误:未选择数据库。这证实了dbforge没有使用$this->newDb->database这一事实,它更喜欢使用硬编码值。

回答

0

对于那些对答案感兴趣的人,在这里。

这个技巧很简单:因为我不能同时打开我的2个数据库,所以我只是使用$ this,就像处理默认数据库一样。我们假设在配置文件中,我有一个名为'newbase'的第二个组,其中有一个空的'数据库'字段。

用户在设置过程中给出了这个名字。

因此,一旦创建了DB和联接关闭:

$this->load->database('newbase', True);  
$this->db->database = '$database'; 

使用$this->db->database为了知道正在处理什么分贝。

然后宣布$ linkfields同上,只需调用dbforge类:

$this->load->dbforge(); 
$this->dbforge->add_field($linkfields); 
$this->dbforge->add_key('table_id', TRUE); 
$this->dbforge->create_table('Link');