从Codeigniter MySQL中的另一个数据库获取数据

1mrurvl1  于 2022-12-06  发布在  Mysql
关注(0)|答案(2)|浏览(129)

我想从MySQL中的另一个数据库中获取数据,除了默认的数据库。除了现有的代码,我在我的模型中添加了下面一行。另一个数据库为“storesDB”。

$this->load->database('storesDB', TRUE);

我的模型为:

public function getEquipment($id = null)
    {  
        $this->db->select('*');
        $this->db->from('tbl_equipment');
        $this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
        $this->db->where("tbl_equipment.status", '1');
        if ($id)
            $this->db->where("tbl_equipment.id", $id);        
            $query = $this->db->get();
        return $query->result();
    }

代码工作正常。但代码从默认数据库而不是“storesDB”获取数据。
修改后的代码如下:

public function getEquipment($id = null)
    {       
        $this->load->database('storesDB', TRUE);
        $this->db->select('*');
        $this->db->from('tbl_equipment');
        $this->db->join('tbl_equipment_category', 'tbl_equipment.eq_cat=tbl_equipment_category.id_cat');
        $this->db->where("tbl_equipment.status", '1');
        if ($id)
            $this->db->where("tbl_equipment.id", $id);        
            $query = $this->db->get();
        return $query->result();
    }

可能是什么原因呢?

cngwdvgl

cngwdvgl1#

原因是您没有正确地分配第二个数据库。

$config['hostname'] = "host";
$config['username'] = "user";
$config['password'] = "pass";
$config['database'] = "storesDB";
// etc..

然后加载数据库:

$this->db2 = load->database($config, TRUE);

现在您有了默认数据库$this->db和第二个数据库$this->db2
并继续执行代码,如下所示:

$this->db2->select('*');
$this->db2->from('tbl_equipment');
// etc...
cig3rfwq

cig3rfwq2#

我没有Codeigniter方面的经验,但是在标准的sql查询中,您可以在表前面添加数据库名称,以从另一个数据库获取信息,如:
请从www.example.com中选择 *sakila.actor;
假设您没有连接到sakila数据库。
使用此方法时,两个数据库必须具有相同凭据

相关问题