2016-08-31 24 views
1

我需要連接到database.php配置文件中尚未定義的數據庫。Codeigniter動態更改爲未定義數據庫

它尚未定義,因爲有超過200個可能的數據庫。

我將循環訪問我的客戶端表以獲取他們的客戶端代碼,以確定當前正在使用哪個數據庫。

我與循環中的字符串是這樣產生的數據庫名稱:

$db_name = "db_".$row['code']; 

從此,我需要連接到一個新的數據庫,這將遍歷數據庫的表來檢查這個數據庫和主數據庫同步。

我嘗試下面的代碼,但它似乎並沒有工作:

$this -> db -> database = $db_name; 

,我也試圖定義在配置這樣的空白連接:

$db['temp'] = $db['default']; 
$db['temp']['database'] = ""; 

,然後改變生成的數據庫名稱與

$this -> db -> database = $db_name; 

功能,但沒有奏效。

我不確定這是否在所有possibe,但這是我可以找到關於如何切換數據庫連接。

如果您有其他建議,請告訴我。

感謝名單提前爲

回答

1

您可以在CodeIgniter Documentation發現數據庫的switching可能是獲取信息,而無需大量腹脹配置文件的唯一的,明智的方式。所以假設地說:

$db_config = array(
    //Shared values 
    'hostname' => '...', 
    'dbdriver' => '...'; 
); 

$all_results = array(); 

$getDatabases = $this->database_model->get_databases(); 
foreach($getDatabases as $key => $row) 
{ 
    $client_db = null; 
    $db_forge = null; 

    $db_name = "db_". $row['code']; 

    //Use copy of shared DB Values. 
    $active_config = $db_config; 
    $active_config['database'] = $db_name; 

    $client_db = $this->load->database($active_config, TRUE); 
    $db_forge = $this->load->dbforge($client_db, TRUE); 

    $result = 
     $client_db->select("*") 
       ->get_where("TB_EXAMPLE", array("client_id" => '...'))->row(); 

    //Example of reason to drop the table 
    if (!empty($result) && $result->INACTIVE == TRUE) 
    { 
     $db_forge->drop_table("TB_EXAMPLE"); 
    } 

    //Now finished with this connection to this particular Database. 
    $client_db->close(); 
    $all_results[] = $result; 
} 

然而,這是非常不明智的。它顯然會連接到200個不同的數據庫,密集且昂貴。如果它們都在同一臺服務器上;不同的數據庫對SELECT會更好,而不是連接到它們。

+0

Thanx!所有這個函數將會循環遍歷表和他們的字段來檢查表是否是最新的。所以我一次只能連接到一個數據庫,但是我沒有辦法手動連接到每個數據庫,所以我希望這發生在循環 –

+0

這實際上是完美的,但你沒有任何機會知道如何在上面使用dbforge,因爲'client_db - > dbforge - > drop_table()'和'$ client_db - > drop_table()'似乎不起作用 –

+0

您需要單獨加載'dbforge'庫它似乎在文檔中提出的'load-> database'。然後它會是'$ this-> dbforge-> drop_table('name');' - 我會在答案中編輯:) – MackieeE