2013-05-20 80 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,因为即使它只是不工作,也会创建对象及其方法。 –

相关问题