• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Select database dynamically

Hello, I got the following scenery:

My app receives an authenticated user from another external app. When the user comes to my app I must to set some session vars like: user_id, account, database, etc.

My big problem is: Codeigniter by default initializes database settings when the library is called from autoload file. I would like to load database settings from an specific file, something like: config/database/database1.php, config/database/database2.php, etc., because will be used many databases.

I'm not an expert programmer, I can do some ugly hacks with cookies or php native sessions but I think that's not right.

I've tried some hooks like this (pre_controller):

PHP Code:
$database $ci->session->userdata('database');


But it does not works for me. Any help or advice?  Huh

Sorry for my bad english, thanks.

Your code should work.  You have to make sure that you have the string $database is defined in


For example, if $database = 'testdatabase', you should have an entry in database.php similar to below:

PHP Code:
$db['default'] = array(
'dsn'    => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE

When you pass a variable to $ci->load->database($variable, TRUE), you're saying, find me the database connection with this name in database.php

(03-29-2015, 12:55 PM)radiohead Wrote:
PHP Code:
$database $ci->session->userdata('database');


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.