在codeigniter中的database.php中获取SESSION值

时间:2015-04-15 14:37:28

标签: php codeigniter session

我在codeigniter中创建了一个项目,但该项目有多个DBS。它运作良好,但我希望根据用户表详细信息调用一个数据库

在data.php文件中的

我希望加载会话用户名来查询

我做了以下

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

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

我做错了什么?

1 个答案:

答案 0 :(得分:0)

正如@Tpojka在评论中所说,你不应该在database.php中这样做。您可以动态选择数据库并在查询之前获取实例。检查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;

在你的模特中,

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
}

希望它对你有用。