For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Connect to Database in CodeIgniter 4

Database Configuration

CodeIgniter has a config file that lets you save your database connection values. The config file is located at app/Config/Database.php. You can also set database connection values in the .env file.

app/Config/Database.php

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'database_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => TRUE,
        'DBDebug'  => TRUE,
        'cacheOn'  => FALSE,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => FALSE,
        'compress' => FALSE,
        'strictOn' => FALSE,
        'failover' => [],
];

Configuring With .env File

You can also save your configuration values within a .env file with the current server’s database settings.

database.default.username = 'root';
database.default.password = '';
database.default.database = 'ci4';

Connecting to your Database

You can connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class.

$db = \Config\Database::connect();

Connecting with Custom Settings

You can pass in an array of database settings instead of a group name to get a connection that uses your custom settings.

$custom = [
            'DSN'      => '',
            'hostname' => 'localhost',
            'username' => '',
            'password' => '',
            'database' => '',
            'DBDriver' => 'MySQLi',
            'DBPrefix' => '',
            'pConnect' => false,
            'DBDebug'  => (ENVIRONMENT !== 'production'),
            'cacheOn'  => false,
            'cacheDir' => '',
            'charset'  => 'utf8',
            'DBCollat' => 'utf8_general_ci',
            'swapPre'  => '',
            'encrypt'  => false,
            'compress' => false,
            'strictOn' => false,
            'failover' => [],
            'port'     => 3306,
    ];
$db = \Config\Database::connect($custom);