Yii 1.1: Multiple Databases and Multiple Domains


How to connect to two databases simutaneously

Add these lines in /config/main.php

            'connectionString' => 'mysql:host=localhost;dbname=database1',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => 'itsasecret',
            'charset' => 'utf8',
            'class' => 'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=database2',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => 'itsasecret',
            'charset' => 'utf8',

Create a new file in protected/components, this example is called AltActiveRecord.php

abstract class AltActiveRecord extends CActiveRecord
    const BELONGS_TO='CBelongsToRelation';
    const HAS_ONE='CHasOneRelation';
    const HAS_MANY='CHasManyRelation';
    const MANY_MANY='CManyManyRelation';
    const STAT='CStatRelation';
     * @var CDbConnection the default database connection for all active record classes.
     * By default, this is the 'db' application component.
     * @see getDbConnection
    public static $db;
    private static $_models=array();            // class name => model
    private $_md;                               // meta data
    private $_new=false;                        // whether this instance is new or not
    private $_attributes=array();               // attribute name => attribute value
    private $_related=array();                  // attribute name => related objects
    private $_c;                                // query criteria (used by finder only)
    private $_pk;                               // old primary key value
     * Returns the database connection used by active record.
     * By default, the "db" application component is used as the database connection.
     * You may override this method if you want to use a different database connection.
     * @return CDbConnection the database connection used by active record.
    public function getDbConnection()
            return self::$db;
            // Create CDbConnection and set properties
            self::$db = new CDbConnection();
            foreach(Yii::app()->db2 as $key => $value)
                self::$db->$key = $value;
        // Uncomment the following lines to prove that you have two database connections
            echo '<br />';
            if(self::$db instanceof CDbConnection)
                return self::$db;
                throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));

For each model using the second database,extend the above file example;

 * This is the model class for table "pagedata".
class Pagedata extends AltActiveRecord
// model stuff here

Your application should now have access to two databases simultaneously.

Multiple Domains with one entry script

Now for multiple sites (multiple domains) using one installation of Yii and one entry script, example parked domains.

Modify index.php as shown below.

// change the following paths if necessary
$hostname = $_SERVER['SERVER_NAME'];
switch ( strtolower($hostname))
case 'example1.com';
case 'www.example1.com';
    // database 1
case 'example2.com';
case 'www.example2.com';
    // database 2
case 'example3.com';
case 'www.example3.com';
    // database 3 
// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);

In each config file you can specify numerous parameters that are site specific.

// application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
        // this is used in contact page

For example styling could be set for each domain name like this (in layout.php)

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/<?php echo Yii::app()->params->cssfile; ?>.css" />

I hope this helps someone


Total 2 comments

#4432 report it
phreak at 2011/07/08 09:53am
Transaction not working

By creating another instance of CDBconnection it will not use the active transcation of the db component. You shoul just return Yii::app()->db2 instead of making a copy of the params.

#3522 report it
WallTearer at 2011/04/17 02:28pm

Thanks a lot, man, for the hint about multiple databases. Worked for me after the first run, very nice, thanks!

Leave a comment

Please to leave your comment.

Write new article