Database Configuration

📘 CodeIgniter 👁 31 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Database Configuration in CodeIgniter (CodeIgniter 4)

CodeIgniter provides a simple and flexible way to configure and manage database connections using configuration files and environment variables.


1. Supported Databases

CodeIgniter 4 supports:

  • MySQL / MariaDB

  • PostgreSQL

  • SQLite

  • SQL Server

  • Oracle


2. Database Configuration Location

You can configure the database in two ways:

  1. Using .env file (Recommended)

  2. Using app/Config/Database.php


3. Database Configuration Using .env (Recommended)

Rename the env file:

cp env .env

Edit .env:

database.default.hostname = localhost database.default.database = mydatabase database.default.username = root database.default.password = database.default.DBDriver = MySQLi database.default.DBPrefix = database.default.port = 3306

✔ More secure
✔ Easy to change per environment


4. Database Configuration Using Database.php

File:

app/Config/Database.php

Example:

public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'mydatabase', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => true, 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'port' => 3306, ];

5. Setting Environment Mode

In .env:

CI_ENVIRONMENT = development

This enables:

  • Detailed database error messages

  • Debugging support


6. Connecting to the Database

Automatic Connection (Model)

$model = new UserModel();

Manual Connection

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

7. Testing Database Connection

Create a controller method:

public function testDB() { $db = \Config\Database::connect(); if ($db->connect()) { echo "Database Connected Successfully"; } }

8. Multiple Database Connections

Add another configuration:

public $testDB = [ 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'test_db', 'DBDriver' => 'MySQLi' ];

Connect:

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

9. Database Prefix

database.default.DBPrefix = ci_

Table name:

ci_users

10. Enable Query Logging

In Database.php:

'DBDebug' => true,

Logs stored in:

writable/logs/

11. Security Best Practices

✅ Use .env for credentials
✅ Disable DBDebug in production
❌ Never commit .env to Git


Summary

  • Configure DB using .env or Database.php

  • Supports multiple databases

  • Secure & environment-based setup

  • Easy connection via models or services


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes