codeigniter中的多个数据库

时间:2010-01-23 22:21:05

标签: php codeigniter frameworks

我正在尝试在CI中实现多个数据库。我的代码在这里:

//database.php
$active_group = "default";
$active_record = TRUE;

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

$db['smf']['hostname'] = "localhost";
$db['smf']['username'] = "root";
$db['smf']['password'] = "root";
$db['smf']['database'] = "smf";
$db['smf']['dbdriver'] = "mysql";
$db['smf']['dbprefix'] = "smf_";
$db['smf']['pconnect'] = TRUE;
$db['smf']['db_debug'] = TRUE;
$db['smf']['cache_on'] = FALSE;
$db['smf']['cachedir'] = "";
$db['smf']['char_set'] = "utf8";
$db['smf']['dbcollat'] = "utf8_general_ci";

模型是

//user_model.php
class user_model extends Model {
    private $ravelex_db;
    function user_model() {
        parent::Model();
        $this->ravelex_db = $this->load->database('default', TRUE);
    }

    function find_all() {
        print_r($this->ravelex_db);
        $q = $this->ravelex_db->get('users');
        return $q->result();
    }
}

//smf_user_model.php
class smf_user_model extends Model {
    private $smf_db;

    function smf_user_model() {
        parent::Model();
        $this->smf_db = $this->load->database('smf', TRUE);
    }

    function find_all() {
        $q = $this->smf_db->get('members');
        return $q->result();
    }
}

控制器测试仪

    class mutipledb extends Controller {

    function mutipledb() {
        parent::Controller();
        $this->load->database();
        $this->load->model('user_model');
        $this->load->model('smf_user_model');
    }

    function index() {
        print_r($this->user_model->find_all());
        print_r($this->smf_user_model->find_all());
    }
}

有一些错误,第一个数据库使用第二个数据库名称。但它仍然使用它的前缀。

错误是

A Database Error Occurred
Error Number: 1146
Table 'smf.rvx_users' doesn't exist
SELECT * FROM (`rvx_users`)

2 个答案:

答案 0 :(得分:0)

在控制器测试文件中,请注释该行:           $这 - >负载>数据库();

将解决问题

答案 1 :(得分:0)

codeigniter中存在错误。在一个类中插入一行将解决整个问题。以下是原始来源:http://koorb.wordpress.com/2007/11/16/codeigniter-connect-to-multiple-databases/

这是一个副本,以防网站出现故障。

行号已更改。以下是codeigniter的错误修复:

-----启动bugfix -----

描述

所有数据库调用都转到同一个数据库(最后一次初始化)

要解决此问题,请更改/system/database/DB_driver.php中的simple_query函数:

function simple_query($sql)
{
    if ( ! $this->conn_id)
    {
        $this->initialize();
    }

    $this->db_select(); //<-----------------  Added this line
    return $this->_execute($sql);
}

---结束BUGFIX ----

这完全解决了这个问题,所以你可以在模型中做这样的事情

$ this-&gt; legacy_db = $ this-&gt; load-&gt; database('legacy',true);