Connecting backend CodeIgniter to two databases after receiving an API call

The use case I got was to connect to a 2nd Db, to retrieve data from a 2nd database and respond with a JSON string, the request would come in as an API call that looks like this “localhost/api/1/noonreport?API-KEY=oBThDgLsHOi8WJpwgf6IvJVQQ45E9LTudUN9i1RL”

I’m using CodeIgniter in the backend server, with MVC and RESTful API support.


The first thing I did was to change the file database.php to add an additional database group to the configuration, like this

database_php

As you can see I added a 2nd database group and called it noon, the default group will be loaded automatically during $this->db call.

Then I created a new API function for noonreport as shown here

noonreport_php

As you can see I connected to the 2nd database, I fetch the data I needed from the 2nd database – closed the 2nd database connection and created a JSON response, that is all.

If you need help or would like to ask a question, please comment.


Posted

in

,

by

Comments

One response to “Connecting backend CodeIgniter to two databases after receiving an API call”

  1. olidev Avatar
    olidev

    Great tip. However, it should also be explained that developers should make it a practice to make sure to close the database connection manually once the code doesn’t require the connection anymore. source: https://www.cloudways.com/blog/connect-multiple-databases-codeigniter/

Leave a Reply to olidev Cancel reply

Your email address will not be published. Required fields are marked *