PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 26, 2022

[FIXED] Yii multiple database connections

 January 26, 2022     mysql, php, yii     No comments   

Issue

I have a three databases, every database has the same table with the same fields, but I don't know how to get all records from all of three databases at the same time in Yii.

Please help


Solution

1.We will start with configuring DB connections. Open protected/config/main.php and define a primary connection as described in the guide:

'db'=>array(
        'connectionString' => 'mysql:host=localhost;dbname=db1',
        'emulatePrepare' => true,
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ),

2.Then copy it, rename the 'db' component to 'db2' and change the connection string accordingly. Also, you need to add the class name as follows:

'db2'=>array(
    'class'=>'CDbConnection',
    'connectionString' => 'mysql:host=localhost;dbname=db2',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
),

3.Then copy it, rename the 'db' component to 'db3' and change the connection string accordingly. Also, you need to add the class name as follows:

'db2'=>array(
    'class'=>'CDbConnection',
    'connectionString' => 'mysql:host=localhost;dbname=db2',
    'emulatePrepare' => true,
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
),

4.That is it. Now, you have two database connections and can use them with DAO and query builder as follows:

$db1Rows = Yii::app()->db->createCommand($sql)->queryAll();
$db2Rows = Yii::app()->db2->createCommand($sql)->queryAll();
$db3Rows = Yii::app()->db2->createCommand($sql)->queryAll();


Answered By - Nanhe Kumar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing