Welcome Guest, Not a member yet? Register   Sign In
Using Dynamic Database Names
#1

(This post was last modified: 10-31-2024, 05:52 PM by occitan.)

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'); 
Reply
#2

$this cannot be used in properties. You need to pass the config as array directly.
https://codeigniter4.github.io/userguide...m-settings
Simple CI 4 project for beginners codeigniter-expenses ( topic )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB