Using multiple database connections with Yii framework
There may be occasions where you will need to set up database connections to more than one database. This guide will show you the easy way to set up these resources.
In your main.php config file, you may already have a db component set up by default.
//.. main.php 'db'=>array( 'connectionString' => 'mysql:host=localhost;dbname=testdrive', 'emulatePrepare' => true, 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', ),
This will be enabled by default. Now, if you want to enable another connection component, simply add another CDbConnection component and give it a different name.
//.. main.php
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
),
'db2'=>array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=database2',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
),
Now, in your models you can pass the connection instance using getDbConnection()
class DbTable extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function getDbConnection()
{
return Yii::app()->db2; // select the connection you want
}
//.. etc
Using this technique you can have your model classes connect to numerous databases.
Enjoy
5 Responses to “Using multiple database connections with Yii framework”
5-26-2010
Why don’t you use Asp.net — or if you want full control of the HTML output, then choose Asp.net MVC — It’s much more efficient and easier. It doesn’t hurt to give it a try!
5-26-2010
Because PHP my prefered web programming language, OpenSource programming/development fits my development values, I already have ‘full control’ over HTML output and I see no benefit learning ASP.NET.
6-21-2010
Nice work with the slider, Kevin. Thanks, and best regards.
7-13-2010
Perfect, now I don’t need mysql_connect() anymore
7-15-2010
Thank u ——– U have saved my lots of time—
‘class’ => ‘CDbConnection’,
I had no idea that I have to include the above line.
Thank u…
Leave a Reply