Change The Db Connection On Fly

Hi Yii world !

                 	I have a problem that, I have different clients with same DB  structure, now after login by any user from any company I have to connect the DB for application according to that user, plz suggest how I should handle this............Thank you all

You would probably need to use the onBeginRequest behavior to intercept the db connection. Take a look at the Application Life Cycle in the Guide. Also, the last part of this wiki provides a practical example on how to do it.

I tried to change the db on fly, its working but the problem is unable to assign the dynamic name, static name its working …

my code is…





            	if (isset(Yii::app()->user->id) && !empty(Yii::app()->user->id))

           	{

                	$user=Users::model()->findByAttributes(array('login_name'=>Yii::app()->user->id));

      	

                	$db_name = strtolower($user->db_name);

  

                    	try

                    	{

                            	Yii::app()->db->setActive(false);


                            	Yii::app()->db->connectionString = "mysql:host=localhost;dbname=".$db_name;	// NOT WORKING


                            	Yii::app()->db->connectionString = "mysql:host=localhost;dbname=any_db_name;" ;  	//wORKING IF DIRECTLY GIVING HARD VALUE

                    	

      	                           Yii::app()->db->username ='root';

                                	Yii::app()->db->password = '';

                           	

                                 	Yii::app()->db->setActive(true);

                                	

                    	}



the error showing is…

CDbCommand failed to execute the SQL statement: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.

please help anyone, its urgent.

It seems that your code is correct. I’ve tested this code and it works:




// run the command with the current connection 

$cmd = Yii::app()->db->createCommand("SELECT * FROM table");

$result = $cmd->query();

foreach($result as $row)

{

   echo("<p>Col1 : {$row['col1']}</p>");

   echo("<p>Col2 : {$row['col2']}</p>");

}

echo('<hr>');


// run the command with the another connection

$db_name = "newdb";

Yii::app()->db->setActive(false);

Yii::app()->db->connectionString = "mysql:host=localhost;dbname=".$db_name;

Yii::app()->db->setActive(true);

$cmd = Yii::app()->db->createCommand("SELECT * FROM table");

$result = $cmd->query();

foreach($result as $row)

{

   echo("<p>Col1 : {$row['col1']}</p>");

   echo("<p>Col2 : {$row['col2']}</p>");

}



Thanks Masoud and JFReyes for your reply