In this post I am going to share useful tip for CakePHP Developer, Few days back i have shared tutorial about How to connect How to connect multiple database in PHP, MYSQLi & PDO. Here I’ll talk about the same thing in CakePHP, In Big web portal they uses multiple database to display data from multiple database tables, In cakePHP their is flexibility to connect n number of databases easily, Without affection your project code. It’s awesome to work with n number of databases in single application.
First open app/Config/database.php file in any code editor. After that find class “DATABASE_CONFIG” and add your other’s database configuration.
class DATABASE_CONFIG { public $default = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'username', 'password' => 'password', 'database' => 'dbname', 'prefix' => '', //'encoding' => 'utf8', ); public $db2 = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'username', 'password' => 'password', 'database' => 'dbname2', 'prefix' => '', //'encoding' => 'utf8', ); public $db3 = array( 'datasource' => 'Database/Mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'username', 'password' => 'password', 'database' => 'dbname3', 'prefix' => '', //'encoding' => 'utf8', ); } |
The default database is public $default , if you want to use other database(db2, db3) you need to initialize new database in your Model using $useDbConfig predefined cakephp method see example.
Calling db2 for model Employee
App::uses('AppModel', 'Model');
class Employee extends AppModel {
public $name = 'Employee';
public $primaryKey = 'id';
public $useDbConfig = 'db2';
}
?>
|
Calling db3 for model Company
App::uses('AppModel', 'Model');
class Company extends AppModel {
public $name = 'Company';
public $primaryKey = 'id';
public $useDbConfig = 'db3';
}
?>
|