DB Forge,Code Igniter和动态数据库选择

时间:2016-08-12 15:09:47

标签: php database codeigniter dbforge

我想从数据库动态切换到另一个数据库,其名称已由用户动态提供。

以下是我的代码的一些有意义的片段:

//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这一事实,它更喜欢使用硬编码值。

1 个答案:

答案 0 :(得分:0)

对于那些对答案感兴趣的人,请点击这里。

诀窍很简单:因为我没有让我的2个dbs同时打开,所以我只使用了$ this,好像我正在处理默认数据库。让我们假设在配置文件中,我有一个名为'newbase'的第二个组,其中包含一个空的'database'字段。

用户在设置过程中提供此名称。

因此,一旦创建了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');