nasaa
nasaa

Reputation: 2731

Setting Database in codeigniter based on the URL (dynamically)

I am using codeigniter to develop my web based application. This will be used by various different clients and each will have there own database but same codebase.

I want to be able to set the name of database in database.php based on the clients who access it i.e based on the url. So if clientA.com access its then it should set the database name to clintA and if clientB.com access it then it should set it to clientB.com.

Any idea as how should I approch this.

Upvotes: 1

Views: 1335

Answers (1)

davidethell
davidethell

Reputation: 12018

There are several possible ways, but probably the easiest is to use database groups in your config file. In your application/config/database.php file use a multi-dimensional array to create different groups for each of your clients. So you could have:

$db['clientA']['hostname'] = ...
$db['clientA']['username'] = ...
etc...
$db['clientB']['hostname'] = ...
$db['clientB']['username'] = ...
etc...

Now in your application you can just pass the desired group to your load command:

$this->load->database('clientA');

Now combine that with getenv to grab the host name and you should be all set:

$clientHost = getenv('HTTP_HOST');
$this->load->database($clientHost);

Of course there could be more logic needed, but that should get you started.

Upvotes: 4

Related Questions