douzhi6365 2014-04-11 12:53
浏览 37
已采纳

尽管存在Yii框架数据库连接,我是否可以建立备用数据库连接

We do application in yii framework working with mysql db connection defined in config.php file. Yet for some reason we want to connect to other server mysql db. Can i do it just this way (without using existent connection):

public function init_db() 
{ 
    $db_handler = mysqli_connect('http://xxx.xxx.xxx.xxx', 'name', 'password', 'db_name');
    $db_handler->set_charset('utf8');

    // check connection 
    if (mysqli_connect_errno()) {
        throw new Exception ("Error connecting to DB : " . mysqli_connect_error()  );
    }              

    // set autocommit to off 
    mysqli_autocommit($db_handler, FALSE);

    mysqli_query ($db_handler, "set time_zone='Europe/Minsk'");

    return $db_handler;
}

As i try it, i get the error: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: hostname nor servname provided, or not known

on this line $db_handler = mysqli_connect('http://xxx.xxx.xxx.xxx', 'name', 'password', 'db_name');

Is there any workaround, hack to get short time connection to fetch some data from external server (not localhost)?

UPDATE

I've just run into this tread. Yet as i try:

$connection=new CDbConnection($dsn,$username,$password);
$connection->active=true;

the yii issues CDbException:

CDbConnection failed to open the DB connection: could not find driver

  • 写回答

1条回答 默认 最新

  • doujugu1722 2014-04-11 13:03
    关注

    In your config file just add another connection settings:

        'db' => array(
            'connectionString' => 'mysql:host=127.0.0.1;dbname=test',
            ....
        ),
        'otherDb' => array(
            'connectionString' => 'mysql:host=127.0.0.1;dbname=test2',
            ....
        ),
    

    And use it like Yii::app()->otherDb

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?