Welcome Guest, Not a member yet? Register   Sign In
Switch Database
#2

(This post was last modified: 04-13-2020, 06:37 PM by cyberstunts.)

Documentation on Working With Databases provides with 2 straight forward ways:

  1. Define groups in configuration
  2. Load custom connection during page execution


In more detail:

Option 1:

Add connections by copy, pasting and renaming 'public $default' to e.g. 'public $my_db_1', 'public $my_db_2', and when want to choose which one to use, just load the DB config you added with:

  
PHP Code:
$db_1 = \Config\Database::connect('my_db_1');
$db_2 = \Config\Database::connect('my_db_2');

// Or choose group dynamically based on your defined database connections e.g.
$db_name 'my_db_' $db_number;    // app/Config/Database.php definitions of groups still apply
$db = \Config\Database::connect($db_name); 

Option 2:

Similar initiation, just instead passing an array which you can change while running your model:

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,
    ];

// Wrap in IF with your logic for database connections
    $custom['database'] = 'DB3';
// End if

$db = \Config\Database::connect($custom); 

EDIT:

Just realised that you posted under CI3.

Your requirement is supported out of the box even in CI3, described here in "Connecting to your Database". There's all the flexibility you need. The logic is the same. 

I will leave CI4 version as is.
Reply


Messages In This Thread
Switch Database - by federcla - 04-13-2020, 10:44 AM
RE: Switch Database - by cyberstunts - 04-13-2020, 05:04 PM
RE: Switch Database - by federcla - 04-14-2020, 03:43 AM
RE: Switch Database - by cyberstunts - 04-14-2020, 05:41 AM



Theme © iAndrew 2016 - Forum software by © MyBB