To dynamically switch databases in Yii2, you can configure your application’s database component at runtime. This is useful when you need to connect to different databases based on certain conditions, like user input, environment, or multi-tenant systems.
Steps to Switch Database Dynamically in Yii2:
Step 1: Define the Default Database Connection in config/db.php
Set up a default database connection in your configuration file (config/db.php), which can act as the base configuration.
‘class’ => ‘yii\db\Connection’,
‘dsn’ => ‘mysql:host=localhost;dbname=default_db’,
‘username’ => ‘root’,
‘password’ => ”,
‘charset’ => ‘utf8’,
];
Step 2: Modify the Database Connection at Runtime
In your controller, model, or anywhere in your application, you can dynamically update the database configuration.
{
// Get the application component for the database
$db = Yii::$app->db;// Dynamically set the new database
$db->close(); // Close any existing connection
$db->dsn = “mysql:host=localhost;dbname=$dbName”;
$db->username = ‘root’;
$db->password = ”; // Replace with actual credentials if needed
$db->charset = ‘utf8’;
// Reopen the connection with the new settings
$db->open();
// Test the connection by running a query (optional)
$command = $db->createCommand(‘SELECT DATABASE()’);
$currentDb = $command->queryScalar();
return “Switched to database: ” . $currentDb;
}
Step 3: Use the Dynamic Connection
Once the database connection is switched, you can use it like any regular Yii2 database connection for executing queries or interacting with models.
For example, after switching the database, any subsequent database operations in that request will use the newly configured database connection.
Step 4: Handling Errors
Ensure that you handle errors gracefully in case the database connection fails (e.g., wrong credentials, database doesn’t exist).
try {
Yii::$app->db->open();
// Proceed with database operations
} catch (\yii\db\Exception $e) {
// Handle the exception
Yii::error("Failed to connect to the database: " . $e->getMessage());
}
Optional: Storing Multiple Database Configurations
If you need to switch between multiple pre-configured databases, you can store their configurations and apply them dynamically:
$databases = [
'db1' => [
'dsn' => 'mysql:host=localhost;dbname=db1',
'username' => 'root',
'password' => '',
],
'db2' => [
'dsn' => 'mysql:host=localhost;dbname=db2',
'username' => 'root',
'password' => '',
],
];// Select the database based on a parameter (e.g., user input)$dbConfig = $databases[$dbName];
$db = Yii::$app->db;
$db->close();
$db->dsn = $dbConfig[‘dsn’];
$db->username = $dbConfig[‘username’];
$db->password = $dbConfig[‘password’];
$db->open();
Conclusion
By updating the db component configuration at runtime, you can switch between different databases dynamically in Yii2. This approach is flexible and can be adapted for various use cases, such as multi-tenant applications or handling different environments.

Leave a Reply