Skip to content

Instantly share code, notes, and snippets.

@rcorsari
Last active January 28, 2024 13:40
Show Gist options
  • Save rcorsari/5e1dc0965ce0f051c49acc6d7f8e737a to your computer and use it in GitHub Desktop.
Save rcorsari/5e1dc0965ce0f051c49acc6d7f8e737a to your computer and use it in GitHub Desktop.
Use Multiple Databases in Codeigniter 4

How to use multiple Databases in a Codeigniter4 app

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment