I am trying to connect to multiple databases in cakephp 3. I have tried many times but all questions and answers are in cakephp 2
I get a solution of my problem. And it's working good. Please refer the below code and comment if I am wrong at any place.
--> app.php
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'nonstandard_port_number',
'username' => 'your_username',
'password' => 'your_password',
'database' => 'tracking_system', // This is my default database
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
],
'db2' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
//'port' => 'nonstandard_port_number',
'username' => 'your_username',
'password' => 'your_password',
'database' => 'tracking_system2', // This is my second database
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'quoteIdentifiers' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
]
]
--> TodolistsController.php
database name: tracking_system2
table name: todolists
use Cake\Datasource\ConnectionManager;
my TodolistsController.php code is:
execute('SELECT * FROM todolists')->fetchAll('assoc');
$this->set('results', $results);
if($this->request->is('post')){
$connection->insert('todolists', [
'title' => $this->request->data['title'],
'description' => $this->request->data['description']
]);
$this->redirect($this->referer);
}
}
}
--> TodolistsTable.php
addBehavior('Timestamp');
}
}
That's it.
Thank You...