Switch Database - 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: Switch Database (/showthread.php?tid=76083) |
Switch Database - federcla - 04-13-2020 Hello everyone I have searched the forum for a solution to my problem but have not found an answer I have to change the name of the database depending on who connects to the web page the only data that changes is the name of the db (DB1, DB2, DB3, DB4 .......) Code: $active_group = 'default'; I have to change only this data 'database' => 'DB1', in the array, passing a variable You can help me? thank you so much RE: Switch Database - cyberstunts - 04-13-2020 Documentation on Working With Databases provides with 2 straight forward ways:
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'); Option 2: Similar initiation, just instead passing an array which you can change while running your model: PHP Code: $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. RE: Switch Database - federcla - 04-14-2020 Option 2: Similar initiation, just instead passing an array which you can change while running your model: PHP Code: $custom = [ sorry but i don't understand very well Do I have to enter this code in each model? Can't I use config/database.php and just pass the database parameter? Thanks a lot for your help RE: Switch Database - cyberstunts - 04-14-2020 I think one of them could suite you when loading a model (from docs): Use this in Controller. PHP Code: $db_config_file = $this->config->load('database'); There're more advanced ways. In CI3, you have plenty of other options. But you will need to try coding it in first to see how things work. You can also load database configuration using config library, then load them into models. I can't guess what will suite you, but you need to see what's on the table and decide what you want to use and make your own approach. Various ways of loading configuration and database connections was especially made for you with dozens of ways to integrate your logic. Controllers and Models are extensible, and could allow you to prepare connection before you load controllers or classes. |