Welcome Guest, Not a member yet? Register   Sign In
possible to assign db_name(Database.php) in a variable or any other option

(This post was last modified: 09-09-2019, 12:51 AM by subodh6580.)

Hello guys
We want to connect one of too many databases as a default.
as per user requriment so we want take a database name in a variable or Global variable.

we are unable to use any variable in Database.php file

so guys help me for this problem.

(This post was last modified: 09-09-2019, 03:48 AM by InsiteFX.)

You can pass the database config group to the database method.

So you would need to setup a config group for each database that you need to use.

PHP Code:
$db1 = \Config\Database::connect('group_one');
$db  = \Config\Database::connect('group_two'); 

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to.


Multiple Connections to Same Database
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )

You can also pass the entire connection group to the connect method:

PHP Code:
$custom = [
'DSN'      => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug'  => (ENVIRONMENT !== 'production'),
'cacheOn'  => false,
'cacheDir' => '',
'charset'  => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre'  => '',
'encrypt'  => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port'     => 3306,
$db = \Config\Database::connect($custom); 

One possible solution to make this a "global" is to create a new method in Config\Services.php that determines which is the correct database to connect to for this page view and return a shared instance of the database connection with the appropriate connection. Then, each time you call that method during that load it will return that same database connection.

Theme © iAndrew 2016 - Forum software by © MyBB