Kindly refer following code snippest to understand what I am trying to achieve,
<?php
function getDBParam()
{
$dbs['test1'] = array('db_name' => 'test1', 'db_user' => 'test', 'db_host' => 'localhost','db_pass' => 'pass');
$dbs['test2'] = array('db_name' => 'test2', 'db_user' => 'test', 'db_host' => 'localhost','db_pass' => 'pass');
$dbs['test3'] = array('db_name' => 'test3', 'db_user' => 'test', 'db_host' => 'localhost','db_pass' => 'pass');
global $global_r;
return $dbs[$global_r];
}
$di->set('db', function(){
$temp = getDBParam();
$array = array(
'host' => $temp['db_host'],
'username' => $temp['db_user'],
'password' => $temp['db_pass'],
'dbname' => $temp['db_name'],
);
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($array);
return $connection;
}
// Code to loop through different db and display the count of records
$records = ['test1', 'test2', 'test3'];
foreach ($records as $r) {
$global_r = $r;
$robots = Robots::find();
echo " \nCount :" . count($robots) . "\n";
}
?>
db test1 has 10 records of Robots,
db test2 has 20 records of Robots,
db test3 has 30 records of Robots,
But while printing it always give count as 10 records i.e. the count of test1 db.
Kindly let me know if there is any way to connect to different Database in a loop?