Saving Data Into Two Different Database's Table

Please help,

[This is my first Yii Project]

  • I have two database db1 and db2

  • There are two tables : ‘member’ in db1 and ‘userinfo’ in db2

  • My registration form successfully connect to table ‘member’ in db1

My question : How to save records from single form into two tables ‘member’ in db1 and ‘userinfo’ in db2?

Please give me steps to do or maybe some code to explain, thank you very much.

Welcome to Yii Family

You can do this is

Controller action

$userinfo= new Users;

$member= new Members;




if($userinf->validate() && $member->validate()){






Hi, pepsikaleng

[size=“2”]I suppose you’re using AR? I’d suggest to follow these basic steps [/size]

  1. Configure one more db connection in your configuration file, for example, under db2 name (usually I use name that describes db but is still short)

  2. Create parent AR class for all your tables/classes from the second db. You may put it under /components

You’ll need to have something like:

class DB2ActiveRecord extends GxActiveRecord{

    public static $db2;

    public function getDbConnection(){

        if(self::$db2 !== null){

            return self::$db2;


            self::$db2 = Yii::app()->db2;

            if (self::$db2 instanceof CDbConnection) {


                return self::$db2;


                throw new CDbException('Active Record requires a "db2" CDbConnection application component.');





  1. Extend db2 classes from relevant parent. You may put them into separate folder if there’re many of them.

  2. tableName() function for these classes should contain db name in returned string, for example:

public function tableName()


        return 'db2.mytable';


And then follow what is Perochak wrote.

Hope I didn’t forget anything, let me know if it’s so :)