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

How to Connect to Multiple Databases in CodeIgniter?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 01:48:10685browse

How to Connect to Multiple Databases in CodeIgniter?

Connecting to Multiple Databases in CodeIgniter

In CodeIgniter, it's possible to connect to multiple databases simultaneously, enabling you to access data from different sources within your application.

Multiple Database Configuration

To establish multiple database connections, you need to first configure your databases in the application/config/database.php file. The default configuration looks like this:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'database_name';
$db['default']['dbdriver'] = 'mysql';

Adding Additional Databases

To add another database connection, create a new array within the $db array. For example, let's add a database named "otherdb":

$db['otherdb']['hostname'] = 'localhost';
$db['otherdb']['username'] = 'otheruser';
$db['otherdb']['password'] = 'otherpass';
$db['otherdb']['database'] = 'other_database_name';
$db['otherdb']['dbdriver'] = 'mysql';

Loading and Using Other Databases

In your model, you can load and use the other database by sending the connection to another variable:

function my_model_method()
{
  $otherdb = $this->load->database('otherdb', TRUE); 

  $query = $otherdb->select('first_name, last_name')->get('person');
  var_dump($query);
}

The TRUE parameter in load->database() indicates that you want to return the database object.

Note:

  • If you don't provide the second parameter to load->database(), the default database will be used.
  • To switch between databases after loading them, use the set_database() method.
  • The CodeIgniter documentation on multiple database connections can be found at http://codeigniter.com/user_guide/database/connecting.html.

The above is the detailed content of How to Connect to Multiple Databases in CodeIgniter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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