2013-05-20 26 views
1

我一直在閱讀幾篇文章以及有關如何連接CI中多個數據庫的官方指南。我目前使用標準database.php配置連接到默認應用程序數據庫,並在需要時動態加載其他數據庫。這部分應用程序的主要目的是具有「導入」功能,用戶用戶在請求時可以即時輸入外部數據庫連接數據。Codeigniter多個數據庫,即使連接失敗,conn_id也會返回對象

只要第二個數據庫連接數據設置正確,應用程序就像一件輕而易舉的事。當連接配置出現錯誤時,我沒有找到一個工作方法來評估無法建立到另一個數據庫的連接。

我發現我可以檢查$ db-> conn_id是否爲最終向用戶返回錯誤,但由於某些原因,無論如何返回一個對象。

這是什麼,我的模型裏面做一個簡單的例子:

function plugin_subscribers_import_sfguard($channel_id) 
{ 
    // Get the channel object by its ID 
    $channel = $this->get_channel_by('id',$channel_id); 

    // Set the preferences for the second database 
    // from the channel informations we retrieved 
    $db['hostname'] = $channel->host; 
    $db['username'] = $channel->user; 
    $db['password'] = $channel->password; 
    $db['database'] = $channel->db; 
    $db['dbdriver'] = "mysql"; 
    $db['pconnect'] = FALSE; 
    $db['db_debug'] = TRUE; 

    // Open the connection to the 2nd database 
    $other_db = $this->load->database($db,TRUE); 

    if (! $other_db->conn_id) 
    { 
     // This never gets executed as $other_db->conn_id always 
     // returns: "resource(34) of type (mysql link)" 
     return false; 
    } 
    else 
    { 
     // Execute the rest of the import script 
     $other_db->select('*'); 
     $other_db->from('sf_guard_user'); 
     $other_db->join('sf_guard_user_profile', 
         'sf_guard_user_profile.id=sf_guard_user.id', 
         'inner'); 
     $query = $other_db->get(); 
    } 
} 

我不知道是否有什麼東西我沒出整個事情,或者如果我使用了錯誤的邏輯以評估輔助數據庫是否打開了正確的連接。

我也嘗試嘗試/趕上沒有成功的連接問題。

在此先感謝您提供的所有支持。 費德里科

回答

0

這是因爲由第二個參數設置爲TRUE(布爾)函數將返回數據庫對象,並在DB.php有一個函數DB最後的代碼塊是

function &DB($params = '', $active_record_override = NULL) 
{ 
    // ... 

    $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; 
    $DB = new $driver($params); 

    if ($DB->autoinit == TRUE) 
    { 
     $DB->initialize(); 
    } 

    if (isset($params['stricton']) && $params['stricton'] == TRUE) 
    { 
     $DB->query('SET SESSION sql_mode="STRICT_ALL_TABLES"'); 
    } 

    return $DB; 
} 

所以,我想想,如果你把這個

$other_db = $this->load->database($db,TRUE); 

wiuthout的TRUE

$other_db = $this->load->database($db); 

然後它可以給你一個不同的結果。

更新:如果我要使用

$other_db = $this->load->database($db,TRUE); 

,那麼你還可以檢查使用method_exists功能的方法可用,像

$other_db = $this->load->database($db,TRUE); 
if(method_exists($other_db, 'method_name')) { 
    // ... 
} 
+0

還有爲TRUE PARAM一個原因:我從代碼中可以看到,需要爲第二個數據庫上的查詢返回的對象:CodeIgniter文檔也詳細記錄了該對象。 無論如何,我試過了,結果是「bool(false)」,在任何情況下......這顯然不是我所需要的。 –

+0

我認爲這是給一個空的物體,不是嗎? –

+0

這是一個有趣的建議,但我嘗試了method_exists,它始終返回true,因爲即使它只是不工作,也會創建對象及其方法。 –

相關問題