Home >Database >Mysql Tutorial >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:
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!