-1

I am trying to connect a db from another server. Is it possible to connect Yii2 db connection from one server to another server db?

3 Answers3

0

In db config you have to specify IP address of your database in your dsn:

'dsn' => 'mysql:host=YOUR_IP_HERE;dbname=YOUR_DB_HERE',

And that's all.

It's possible that second server doesn't allow connections on 3306 port, so you have to allow it in iptables (linux servers).

Yupik
  • 4,932
  • 1
  • 12
  • 26
  • when i specified the ip address and db nameith shows this error "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." – SaabzCoder Sep 21 '17 at 09:38
  • Are you sure that your second server database allows remote connections? – Yupik Sep 21 '17 at 09:40
  • I am giving my server IP, but its taking the IP of the current local-machine. Error Displayed : SQLSTATE[HY000] [1045] Access denied for user 'root'@'192.168.94.196' (using password: NO) – Pravinraj Venkatachalam Mar 22 '18 at 09:51
0

It is very possible, even you can connect yii2 application with many different database server. You just need to add a bit in the configuration file as below:

    'components' => [

    'db_server1' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'pgsql:host=localhost;dbname=DB_NAME;port=PORT_CONNECTION',
        'username' => 'DB_USERNAME',
        'password' => 'DB_PASSWORD',
        'charset' => 'utf8',
    ],

    'db_server2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'pgsql:host=OTHER_HOST;dbname=DB_NAME;port=PORT_CONNECTION',
        'username' => 'DB_USERNAME',
        'password' => 'DB_PASSWORD',
        'charset' => 'utf8',
    ],];

Hope can help you

0

You have to configure another db connection in your web.php inside the config folder:

    'db2'=>[
        'class'=>'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=dbname',
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8'            
    ],

and then you call db2 component.

Pratik Karmakar
  • 247
  • 1
  • 8