This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

CloudwaysCDN — a powerful solution that offers superior performance and satisfied global audience for your business. Read More

Create Multiple Database Connections in CodeIgniter Applications

Updated on  13th September

2 Min Read
Reading Time: 2 minutes

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.

You might also like: How To Host CodeIgniter PHP On Cloud Using SSH

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:

You might also like: How To Use Elasticsearch Codeigniter Library In Your Projects

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.

Share your opinion in the comment section. COMMENT NOW

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

Start Growing with Cloudways Today.

Our Clients Love us because we never compromise on these

THERE’S MORE TO READ.