'Dynamic Database Selection in PHP Mongodb

Not able to select the database and collection dynamically. Read all the solutions but not working for me. selectDB function not working. It's working only with the static data.

I want to select the database from the configuration file and also select the collections dynamically.

$username='abcd';
$password='efgh';
$m = new MongoDB\Client("mongodb://[email protected]:28015/ijkl", array("username" => $username, "password" => $password));

$db = $m->ijkl;

but I want to have it like

$username='abcd';
$password='efgh';
$m = new MongoDB\Client("mongodb://[email protected]:28015/ijkl", array("username" => $username, "password" => $password));

$l1="ijkl";
$db = $m->$l1;

Expecting to work with dynamic database selection.



Solution 1:[1]

Use mongodb client repo from packagist. You can install it via composer

$ composer require mongodb/mongodb

in your root directory, create file for example app.php

<?php

require 'vendor/autoload.php';

$databases = [
 'db1'=> [
    'db' => 'testdb1',
    'username' => 'user',
    'password' => 'pass',
    ...
 ], 
  'db2'=> [...],
  ...
];
$seletected = 'db1';

$database = $databases[$selected];

$client = new MongoDB\Client(
    "mongodb+srv://{$database['username']}:{$database['password']}@<cluster-address>/test?retryWrites=true&w=majority"
);


$db = $client->{$database['db']};

Solution 2:[2]

replace $db = $m->$l1 to $db = $m->{$l1}

$username='abcd';
$password='efgh';
require 'vendor/aoutoload.php';
$m = new MongoDB\Client("mongodb://[email protected]:28015/ijkl", array("username"=> $username, "password" => $password));

$l1="ijkl";

$db = $m->{$l1};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Roshan Gamage