Home > Database > Mysql Tutorial > How Can I Connect to Multiple Databases in CodeIgniter?

How Can I Connect to Multiple Databases in CodeIgniter?

Linda Hamilton
Release: 2024-12-08 00:58:11
Original
1015 people have browsed it

How Can I Connect to Multiple Databases in CodeIgniter?

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template