简体   繁体   中英

GET SESSION value in database.php in codeigniter

I am created a project in codeigniter but the project has multiple DBS. It works well but I am looking to call one DB dependant on the users table details

in the database.php file I wish to load the session username to query

I have done the following

$autoload['libraries'] = array('session');

if(!empty($this->session->userdata('username')))
$username_c = $this->session->userdata('username');

What am I doing wrong?

As @Tpojka said in comment, you shouldn't do it in database.php . You can choose database dynamically and get instance before query from it. Check here .

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "db_one";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;


$db['second_db']['hostname'] = "localhost";
$db['second_db']['username'] = "root";
$db['second_db']['password'] = "";
$db['second_db']['database'] = "db_two";
$db['second_db']['dbdriver'] = "mysql";
$db['second_db']['dbprefix'] = "";
$db['second_db']['pconnect'] = TRUE;
$db['second_db']['db_debug'] = FALSE;
$db['second_db']['cache_on'] = FALSE;
$db['second_db']['cachedir'] = "";
$db['second_db']['char_set'] = "utf8";
$db['second_db']['dbcollat'] = "utf8_general_ci";
$db['second_db']['swap_pre'] = "";
$db['second_db']['autoinit'] = TRUE;
$db['second_db']['stricton'] = FALSE;

In your model,

public function get_profile() {
    if(!empty($this->session->userdata('username'))) {
        $username_c = $this->session->userdata('username');
        $DB2 = $this->load->database('second_db', TRUE); // true to get db instance
        return $DB2->select("*")->from("user")->get()->row(); // query from second DB
    }

    $this->db->select("*")->from("user")->get()->row(); // query from default DB
}

Hope it will be useful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM