I am trying to connect from multiples databases from a loop, but seens CakePHP can't change database
, only others infos (like user/pass/host).
app/Config/database.php
<?php
class DATABASE_CONFIG {
[...]
public $default = array(
[..] // Where I have the companies
);
public $client = array(
[...] // Fakke settings, because I will change it on-the-fly
);
}
app/Controller/CronController.php
$companies = $this->Company->find('all');
foreach($companies as $company) {
$settings = array(
'datasource' => 'Database/Mysql',
'host' => $company['Company']['host'],
'login' => $company['Company']['username'],
'password' => $company['Company']['password'],
'database' => $company['Company']['database'],
);
ConnectionManager::drop('client');
$db = ConnectionManager::create('client', $settings);
try {
debug($this->MyModel->find('first'));
} catch (Exception $e) {
echo '<pre>';
echo "Exception: ", $e->getMessage(), "\n";
/*
debug($this->MyModel->getDataSource());
Outputs:
[...]
[config] => Array
(
[persistent] =>
[host] => 0.0.0.0 // CORRECT HOST
[login] => root // CORRECT LOGIN
[password] => pass // CORRECT PASSWORD
[database] => database1
[port] => 3306
[datasource] => Database/Mysql
[prefix] =>
[encoding] => utf8
)
[...]
*/
}
}
It return the first connection and all others I can select nothing from MyModel, because it is wrong. It seens connection from user/password/host is ok, but, database are not changed, so, because user haven't permission to select on cdatabase, I get the error.
Array
(
// First connection, connection ok, MyModel return nothing
)
// Second connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_2'@'localhost' for table 'my_model'
// Third connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_3'@'localhost' for table 'my_model'
// Fourth connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_4'@'localhost' for table 'my_model'
// Fifth connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_5'@'localhost' for table 'my_model'
Thanks!
You can use the model method setSource() to change the table or setDataSource() to change the db config.
Try not to drop config, just alter the things you need.
For this task I successfully use
I don't know if database switching and mysql as engine is good pair. I use postgresql schemas for this purpose.