Post Date: April 26, 2019
Last Updated: October 21, 2026
Introduction
CodeIgniter is a PHP framework that provides a database abstraction layer for connecting applications to databases and executing queries. Some applications need to connect to multiple databases to manage separate data sources, support legacy systems, or retrieve information from different databases within the same application.
For example, an application might use one database to store user information and another to manage reports, transactions, or historical records.
CodeIgniter supports multiple database connections through its database configuration file. By defining separate connection groups, developers can load and use the required database connection from controllers, models, or other application components.
Prerequisites
Before proceeding, ensure that you have:
- PHP installed with the required database extensions.
- A working CodeIgniter 3 application.
- Access to the application’s
application/config/database.phpfile. - Two databases that are accessible from your application server.
- Database credentials with the required permissions.
- Basic knowledge of PHP and SQL.
The examples below use MySQL with the mysqli database driver. Adjust the hostname, database names, usernames, and passwords to match your environment.
Implementation
Step 1: Locate the Database Configuration File
CodeIgniter 3 stores its database connection settings in:
application/config/database.php
Open this file and locate the default database configuration.
A typical configuration contains the following settings:
hostname: Database server hostname or IP address.username: Database account used for authentication.password: Password for the database account.database: Name of the database to access.dbdriver: Database driver, such asmysqli.pconnect: Whether to use persistent connections.db_debug: Whether database errors are displayed.char_set: Character set used for database communication.dbcollat: Database connection collation.
These settings define how CodeIgniter connects to a database.
Step 2: Configure the First Database Connection
Assume the application uses a database named form as its primary database.
Configure the default connection in application/config/database.php:
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'app_user',
'password' => 'your_secure_password',
'database' => 'form',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Replace the example credentials with the actual database credentials.
For production applications, configure database error handling so that internal connection details and SQL errors are not exposed to end users.
Step 3: Configure the Second Database Connection
To connect to another database, add a second configuration group in the same file.
For example, the second database is named db2.
$db['database2'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'app_user',
'password' => 'your_secure_password',
'database' => 'db2',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
You now have two named connection groups:
default— connects to theformdatabase.database2— connects to thedb2database.
Both configurations use pconnect => FALSE, which avoids requesting persistent database connections. Persistent connections are not required for multiple database access.
If the databases are hosted on different servers, specify the appropriate hostname and credentials for each connection.
Step 4: Load the Second Database Connection
After configuring the connection groups, load the second database using CodeIgniter’s database loader.
For example, create or open a controller at:
application/controllers/DatabaseTest.php
Add the following code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class DatabaseTest extends CI_Controller
{
public function index()
{
// Load the default database connection.
$this->load->database();
// Load the second database connection.
$db2 = $this->load->database('database2', TRUE);
// Test the second database connection.
$query = $db2->query('SELECT DATABASE() AS database_name');
if ($query) {
$result = $query->row();
echo 'Connected database: '
. htmlspecialchars($result->database_name);
} else {
echo 'Unable to execute the database query.';
}
}
}
The important statement is:
$db2 = $this->load->database('database2', TRUE);
The first argument specifies the database configuration group. The second argument, TRUE, tells CodeIgniter to return the database connection object instead of assigning it to the default database property.
You can then use $db2 to execute queries against the second database.
Step 5: Query Both Databases
Once both connections are available, you can execute queries against each database independently.
// Query the default database.
$query1 = $this->db->query(
'SELECT DATABASE() AS database_name'
);
// Load and query the second database.
$db2 = $this->load->database('database2', TRUE);
$query2 = $db2->query(
'SELECT DATABASE() AS database_name'
);
if ($query1 && $query2) {
echo 'First database: '
. htmlspecialchars($query1->row()->database_name);
echo '<br>';
echo 'Second database: '
. htmlspecialchars($query2->row()->database_name);
}
The $this->db property represents the default connection when it has been loaded. The $db2 variable represents the second connection.
For production applications, handle database connection and query failures through appropriate logging and application error handling rather than displaying raw database errors.
Step 6: Use Multiple Connections in a Model
For better code organization, database operations can be placed in a model.
Create the following file:
application/models/Report_model.php
Example:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Report_model extends CI_Model
{
private $report_db;
public function __construct()
{
parent::__construct();
$this->report_db = $this->load->database(
'database2',
TRUE
);
}
public function get_reports()
{
return $this->report_db
->get('reports')
->result();
}
}
This example assumes that the db2 database contains a table named reports.
Load and use the model from a controller:
$this->load->model('Report_model');
$reports = $this->Report_model->get_reports();
This approach separates database access logic from the controller and makes the application easier to maintain.
Step 7: Verify the Database Connections
Test each connection independently before using it in production.
You can run the following query against a connection to verify which database is selected:
SELECT DATABASE();
You can also check whether the database connection is available:
$db2 = $this->load->database('database2', TRUE);
if ($db2->conn_id) {
echo 'Database connection initialized.';
}
A successfully initialized connection does not guarantee that every query will succeed. Verify that the database exists, the credentials are valid, and the account has permission to access the required tables.
For remote databases, also verify network connectivity, firewall rules, and database server access settings.
Step 8: Avoid Unnecessary Framework Core Modifications
The original tutorial proposes modifying:
system/database/DB_driver.php
by adding the following line inside the simple_query() method:
$this->db_select();
This modification should not be required for standard CodeIgniter 3 multiple database connections when the named connection groups are configured and loaded correctly.
Avoid changing framework core files unless a specific, verified defect requires a controlled patch. Core modifications can be overwritten during upgrades and may introduce unexpected behavior.
If the second connection fails, check the configuration group name, database credentials, server access permissions, and the connection-loading method before considering framework-level changes.
Conclusion
CodeIgniter 3 supports multiple database connections through named configuration groups in application/config/database.php.
By defining separate connections and loading them with $this->load->database('database2', TRUE), developers can query different databases within the same application without unnecessarily modifying framework core files.
For maintainable applications, keep database operations in models or dedicated data-access components, use least-privilege database accounts, protect credentials, and handle errors securely.
Version note: This tutorial focuses on CodeIgniter 3. CodeIgniter 4 uses a different database configuration and connection-management approach, so its implementation should follow the CodeIgniter 4 documentation.
Frequently Asked Questions
1. Can CodeIgniter connect to multiple databases?
Yes. CodeIgniter 3 supports multiple database connections through named configuration groups in application/config/database.php.
2. How do I load the second database in CodeIgniter 3?
Use the following statement:
$db2 = $this->load->database('database2', TRUE);
The database2 value must match the configuration group defined in application/config/database.php.
3. Can the two databases be hosted on different servers?
Yes. Each connection group can have its own hostname, credentials, database name, and other connection settings. Ensure that the application server can reach both database servers and that their access controls permit the connections.
4. Is it necessary to set pconnect to TRUE?
No. Persistent connections are not required to connect to multiple databases. Use FALSE unless persistent connections are specifically required and appropriate for your deployment.
5. Do I need to modify DB_driver.php to use multiple databases?
Normally, no. Use CodeIgniter’s supported database loader and configure each connection group correctly. Modifying core framework files can create maintenance and compatibility issues.
6. Can I use different database types in the same application?
CodeIgniter can support different database drivers where the framework version, PHP extensions, and required database features are compatible. Verify driver support and query compatibility for the specific databases involved.
7. How can I troubleshoot a failed second database connection?
Check the connection group name, hostname, port, username, password, database permissions, required PHP extensions, and network connectivity. Review server-side logs without exposing sensitive database details to users.
8. Does the same approach work in CodeIgniter 4?
No. CodeIgniter 4 uses a different configuration structure and database connection API. Follow the official documentation for your installed version.
Official Links
- CodeIgniter Official Documentation
- CodeIgniter 3 Database Configuration
- CodeIgniter 3 Connecting to Multiple Databases
- CodeIgniter 4 User Guide
Related Articles
How to add Google ReCAPTCHA in PHP Codeigniter
Need Assistance with CodeIgniter Development?
Configuring multiple database connections requires careful handling of credentials, database permissions, query execution, and application architecture. Pheonix Solutions can assist with PHP application development, CodeIgniter integration, database configuration, performance optimization, and troubleshooting.
If you need assistance implementing multiple database connections or maintaining your CodeIgniter application, contact Pheonix Solutions to discuss your requirements.