Multiple Database Connections in CodeIgniter
CodeIgniter enables you to establish connections to multiple databases seamlessly. This capability proves particularly useful when you need to retrieve information from one database and use it to connect to another, as you have described.
To accomplish this in CodeIgniter, you can utilize the following approach:
In the application/config/database.php file, define the credentials and settings for the second database. CodeIgniter typically stores the default database settings in an array named $db['default']. To add a new database, create a separate array within the $db array, for example, $db['otherdb'], and provide the necessary information.
Next, in your model, use the load->database() method to load and return the database object for the second database:
function my_model_method() { $otherdb = $this->load->database('otherdb', TRUE); $query = $otherdb->select('first_name, last_name')->get('person'); var_dump($query); }
By passing TRUE as the second parameter to load->database(), you instruct CodeIgniter to return the database object instead of setting it as the default connection. This allows you to interact with multiple databases simultaneously.
This method provides a straightforward and efficient way to work with multiple databases in CodeIgniter, enabling you to retrieve data seamlessly from different sources.
The above is the detailed content of How Can I Connect to Multiple Databases in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!