动态地在codeigniter中添加数据库

时间:2015-07-21 03:59:58

标签: database codeigniter codeigniter-2

我正在使用codeigniter应用,允许用户添加编辑和修改数据库。

我想循环重复这段代码:

$db['db1']['hostname'] = 'localhost';
$db['db1']['username'] = 'ts4l_wp13';
$db['db1']['password'] = 'O&3D6c(0zD70.^9';
$db['db1']['database'] = 'ts4l_wp13';
$db['db1']['dbdriver'] = 'mysql';
$db['db1']['dbprefix'] = '';
$db['db1']['pconnect'] = FALSE;
$db['db1']['db_debug'] = TRUE;
$db['db1']['cache_on'] = FALSE;
$db['db1']['cachedir'] = '';
$db['db1']['char_set'] = 'utf8';
$db['db1']['dbcollat'] = 'utf8_general_ci';
$db['db1']['swap_pre'] = '';
$db['db1']['autoinit'] = TRUE;
$db['db1']['stricton'] = FALSE;

我这样做:

@$get_data = mysql_query("SELECT * FROM `database_name`");
    while($getdata =  mysql_fetch_assoc($get_data)){        
    $id='db'.$getdata['id'];
    $iid="$id";
                     $db["$iid"]['hostname'] = 'localhost';
                     $db["$iid"]['username'] = $getdata['username'];
                     $db["$iid"]['password'] = $getdata['password'];
                     $db["$iid"]['database'] = $getdata['name'];
                     $db["$iid"]['dbdriver'] = 'mysql';
                     $db["$iid"]['dbprefix'] = '';
                     $db["$iid"]['pconnect'] = FALSE;
                     $db["$iid"]['db_debug'] = TRUE;
                     $db["$iid"]['cache_on'] = FALSE;
                     $db["$iid"]['cachedir'] = '';
                     $db["$iid"]['char_set'] = 'utf8';
                     $db["$iid"]['dbcollat'] = 'utf8_general_ci';
                     $db["$iid"]['swap_pre'] = '';
                     $db["$iid"]['autoinit'] = TRUE;
                     $db["$iid"]['stricton'] = FALSE;
    }

和这个街区。

// Loading  db and running query.
        $CI = &get_instance();      
        $this->db1 = $CI->load->database('db1', TRUE);
        $this->db1->set($data);
        $this->db1->insert($this->_table_name);
        $id=$this->db1->insert_id();

我这样做:

$this->load->model('mdb_m');
  $dbms =$this->mdb_m->get();

        if (count($dbms)) {
           foreach ($dbms as $dbm) {
              $mid=$dbm->id;
              $dbc='db'.$mid;
               $CI = &get_instance();   
               $this->db.$mid = $CI->load->database( "$dbc" , TRUE);
               $this->db.$mid->set($data);
               $this->db.$mid->insert($this->_table_name);
           }
        }

但它只插入数组中的第一个数据库,然后停止并检索此错误"您指定了一个无效的数据库连接组。"

1 个答案:

答案 0 :(得分:0)

你可以从这里获得使用多个数据库的简要信息。正如你所提到的。 https://ellislab.com/codeigniter/user-guide/database/connecting.html

为了更好的方法,你可以制作一个加载器文件来加载数据库。我遇到了同样的问题,从这里得到了清晰的可视化

https://coderwall.com/p/_kyjvg/codeigniter-loading-up-multiple-databases

请参考此处,如果仍然感到困惑,请回复给我。谢谢。