first we edit the .env file with
# DEFAULT connection group
database.default.hostname = localhost
database.default.database = codeigniter_db1
database.default.username = myuser
database.default.password = Myuser@123
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
# CUSTOM connection group - otherDb
database.otherDb.hostname = localhost
database.otherDb.database = codeigniter_db2
database.otherDb.username = myuser
database.otherDb.password = Myuser@123
database.otherDb.DBDriver = MySQLi
database.otherDb.DBPrefix =
database.otherDb.port = 3306
then for fallback purposes ALSO accordingly the Database.php
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
public array $otherDb = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
finally in our controller we can use
namespace App\Controllers;
use App\Controllers\BaseController;
class Dashboard extends BaseController
{
private $db1;
private $db2;
public function __construct()
{
$this->db1 = db_connect(); // default database group
$this->db2 = db_connect("otherDb"); // other database group
}
}
full tutorial is available here https://onlinewebtutorblog.com/codeigniter-4-with-multiple-databases/