Vous êtes sur la page 1sur 3

How to Use Two Database in Yii PHP Framework Recently in one of Ireland based project client has requirement

to use existing Microsoft SQL Server database and implement new feature and store data into MySQL database with ii !ramewor"# !irst we have install and implement microsoft sql server driver in wamp server to ma"e in localhost environment# $ow we have to connect both the %atabase in ii !ramewor"# !ollowing is steps to implement in ii !ramewor" & '# In protected(config folder open main#php and add below code in component for mysql and sql server connection
'db'=>array( // default mysql connection

'connectionString' => 'mysql:host=localhost;port=330 ;dbname=db!name'" 'emulate#repare' => true" 'username' => 'db!username'" 'pass$ord' => 'db!pass$ord'" 'charset' => 'utf%'" 'table#refi&' =>'tbl!'" (" 'msdb'=>array( // microsoft sql ser'er connection 'class' => ')*b)onnection'" 'connectionString' => 'sqlsr':Ser'er=host!name or ip!address;*atabase=db!name'" 'username' => 'db!username'" 'pass$ord' => 'db!pass$ord'" 'charset' => '+,-3.-'" (" // if ha'e prefi& in database tables

)# $ow sql server connection is available in your entire application and access by *%b*ommand
/company!name=0ii::app((1>msdb1>create)ommand(2S343)5 56# . )ompany7ame from )ompany!*etails 893:3 )ompany;*=2e<eeli'e2(1>query:o$((; if(isset(/company!name( == >empty(/company!name?2)ompany7ame2@((: echo /company!name?2)ompany7ame2@; // it $ill print company name 3<eeli'e 5echnologies

else: echo ''; endif;

In above example we have use msdb define database connection in component +# Sometime we require to get the data from one table and insert into another database table, In this case you can use create*ommand to write custom loop or you can Switch database connection runtime in model class
class )ompany e&tends )Acti'e:ecord B public function init(( B /this1>attach3'ent9andler('6n,eforeSa'e'" /this1>attach3'ent9andler('6nAfterSa'e'" C public function s$itch5o8riter(( B self::/db=0ii::app((1>db; return true; C public function s$itch5o:eader(( B self::/db=0ii::app((1>msdb; return true; C //DDD C array(/this"'s$itch5o8riter'((; array(/this"'s$itch5o:eader'((;

In above example database connection will swapping means the connection will automatically change in fetching and inserting time# -switch.oReader- function for fetching the data from SQL Server database and -switch.o/riter- for insert(save data into MySQL database#

0lease fill free to contact us on info@ezeelive.com or leave a comment for any type of development, integration and coding problem# 1eep *oding###22

Vous aimerez peut-être aussi