CodeIgniter Forums
How to load databases dynamically in codeigniter - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Development (https://forum.codeigniter.com/forumdisplay.php?fid=6)
+--- Forum: CodeIgniter 3.x (https://forum.codeigniter.com/forumdisplay.php?fid=17)
+--- Thread: How to load databases dynamically in codeigniter (/showthread.php?tid=87120)



How to load databases dynamically in codeigniter - BobbyTanomrfp - 03-15-2023

I'm using Codeigniter 3.X in my application and I want to use different databases for each user dynamically. Currently, the main database is called main_db, but if a user with user id 1 logs in, then I want to use db_1 and so on. While Codeigniter does allow for the use of multiple databases, I want to be able to load them dynamically. Is there a way to achieve this?
Here's my database.php configuration file. In my model construct, I load the database using:
$this->load->database();
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'username',
'password' => 'password',
'database' => 'main_db',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);