Create Multiple Database Connections in CodeIgniter Applications

by Owais Alam  September 13, 2017

In real world CodeIgniter projects, developers need to work with multiple databases at the same time. This presents a unique challenge to developers. Since this is a common enough problem, CodeIgniter offers a simple solution for it.

In order to use multiple database connections in your CodeIgniter project, you just need to create multiple configuration arrays that simplify working with multiple databases.

The Default Configuration Array

Following is the structure of the default Codeigniter database configuration array:

So in order to create another database connection, you should create another configuration array. This array has to follow the same structure. Here is an example of the array:

Connect to the Right Database

At this point, you have two databases in your sample project. To connect to a specific database, you must specify the database name. Here is the proper syntax:

Now if you need to work with the second database, you have to send the connection to a variable that is usable in your model:

Close the Connections

CodeIgniter does close the database connections after it determines that the code no longer need the connection. However, as a good practice, developers should close the connections explicitly. Here is how to take care of the issue:

Conclusion

In this article, I have discussed the problem and the solution to using multiple database connections in CodeIgniter projects. If you need help with implementing the idea in your projects, do leave a comment below and I will get back to you.

Create PHP websites without the worry of server management.

Deploy your PHP app on optimized PHP hosting servers.

About Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at owais.alam@cloudways.com

Stay Connected:

You Might Also Like...