Yii2 Multiple Database Connection : Select database based on login user id, Runtime

his is my scenario.

I have a list of all the Clinic using my application in a ‘main’ database. In the ‘main’, information about each clinic is in a table which also contains columns that for, database name, username and password for the DB. The schema structure is the same for each one.

All these clinics will use the single source code, which I am currently developing in Yii2. What I would need is at the time of login, automatically select the corresponding database, from that all the transaction, must be in the database.

I tried saving Database name in the session.

$db_name = "main";

if( isset($_SESSION['db']) ){
    $db_name = $_SESSION['db'];
}
$config = [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname='.$db_name,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    ],
];

it doesn’t work I can’t access the session in config/main.php.

I can’t do the solution because all clinics have the same SERVER_NAME. Change DB connection Dynamically

At configuration reading time the application didn’t start yet, therefore no session is started.
Try to add session_start();

$db_name = "main";
session_start();
if( isset($_SESSION['db']) ){
    $db_name = $_SESSION['db'];
}
session_start();

But it won’t work

Hi @manuvarghese236;

Why tri using multiples files with same config and include or require in config/web.php any files with instance yii\db\Conecction?

How do you store it? Using yii function?
Did you test the value after storing?

The easiest way is to have common connection for login and that have access to users table. Then after login create a tenant (actual keyword for what you are trying to do) and use the information to query all tenant data. It might be tenant_id if you use same db or db name if you use multiple db.

Don’t forget to override tableName() method with dynamic one.