CodeIgniter Forums
Using Dynamic Database Names - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Using Dynamic Database Names (/showthread.php?tid=91894)



Using Dynamic Database Names - occitan - 10-31-2024

I am trying to create a dynamic database connection from a model and can't seem to do it. 
We have a separate database for each customer, so the database name would be like db_1001, db, 1002, db_1003, etc (production names are more secure). 
The 1001, 1002, 1003 is stored in a session variable when they login. So what I need is below:

PHP Code:
    public array $customer = [
        'hostname'    => 'localhost',
        'username'    => 'fa_customer',
        'password'    => 'abcd1234',
        'database'    => 'db_' $this->session->customer_id',
        ...
        ...
    ]; 

But I get the error:

ErrorException: Constant expression contains invalid operations in APPPATH/Config/Database.php on line 93

I assume because the Database class is static?
So how would I accomplish this?
Can I put the database credentials in the Model?

It's instantiated in the model like this now:

PHP Code:
$customer_db = \Config\Database::connect('customer'); 



RE: Using Dynamic Database Names - ozornick - 10-31-2024

$this cannot be used in properties. You need to pass the config as array directly.
https://codeigniter4.github.io/userguide/database/connecting.html#connecting-with-custom-settings