0

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

Igor Savinkin
  • 5,669
  • 8
  • 37
  • 69

1 Answers1

1

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

Alex
  • 8,055
  • 7
  • 39
  • 61
  • should i disable existing connection while establishing new one? – Igor Savinkin Apr 11 '14 at 13:07
  • no, you can use them both, but if you want to work models with other connections, you must redefine method getDbConnection of ActiveRecord model – Alex Apr 11 '14 at 13:14
  • i did as you've sugested but no avail: CDbException: CDbConnection failed to open the DB connection: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: hostname nor servname provided, or not known. Might be my connectionString is wrong: `'connectionString' => 'mysql:host=http://xxx.xx.xx.xxx;dbname=some_name',` ? – Igor Savinkin Apr 11 '14 at 13:19
  • check this article http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/ – user1852788 Apr 11 '14 at 13:19
  • 1
    remove http-staff, it's not http query :) – Alex Apr 11 '14 at 13:46