Codeigniter,呼叫多个数据库

时间:2016-01-14 14:25:40

标签: php mysql codeigniter

我对codeigniter很新,但处理有关多个db的问题。数据库位于同一主机上。

我已将database.php文件更改为包含一个额外的组,除了'默认'新组称为“社交”

$active_group = 'default';
$active_group = 'social';
$active_record = TRUE;

$db['default']['hostname'] = 'xxxx';
$db['default']['username'] = 'xxx';
$db['default']['password'] = 'xxxx';
$db['default']['database'] = 'mysql';
$db['default']['dbdriver'] = 'mysqli';
$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['social']['hostname'] = 'xxx';
$db['social']['username'] = 'xxx';
$db['social']['password'] = 'xxx';
$db['social']['database'] = 'social';
$db['social']['dbdriver'] = 'mysqli';
$db['social']['dbprefix'] = '';
$db['social']['pconnect'] = TRUE;
$db['social']['db_debug'] = FALSE;
$db['social']['cache_on'] = FALSE;
$db['social']['cachedir'] = '';
$db['social']['char_set'] = 'utf8';
$db['social']['dbcollat'] = 'utf8_general_ci';
$db['social']['swap_pre'] = '';
$db['social']['autoinit'] = TRUE;
$db['social']['stricton'] = FALSE;

现在在我的代码中我调用了dbs

public function __construct()
{
    $dbgroup = !file_exists(".git") ? "default" : "development";
    $this->_time = microtime(true);
    $this->_db =& DB($dbgroup);

    $dbgroup = "social";
    $this->_time = microtime(true);
    $this->_dbs =& DB($dbgroup);

我做错了什么,为什么我不能使用_dbs从第二个数据库中获取数据?请记住......在这里完全编码新手!这不是我的日常工作:)

UPDATE! 尝试在stackoverflow.com/a/8269596中描述的在此函数中调用db,但我仍然无法使其工作。

public function getUsers($userid = NULL)
{
    if (empty($userid) ) {
                $rs = $this->load->database('social', TRUE);
        ->select("id, username")
        ->from("user")
        ->get();
        $userid = $rs->result();
    return $userid;
    }
    elseif (isset($userid)) {
                $rs = $this->load->database('social', TRUE);
        ->select("id, username")
        ->from("user")
        ->where('id', $userid)
        ->get();
        $userid = $rs->result();
    return $userid;
    }
}

1 个答案:

答案 0 :(得分:0)

我认为这应该有效:

public function getUsers($userid = NULL)
{
    $rs = $this->load->database('social', TRUE);
    if (empty($userid) ) {
        $rs->select("id, username")
        ->from("user")
        ->get();
        $userid = $rs->result();
    return $userid;
    }
    elseif (isset($userid)) {
        $rs->select("id, username")
        ->from("user")
        ->where('id', $userid)
        ->get();
        $userid = $rs->result();
    return $userid;
    }
}