我想從 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();
}
可能是什么原因?
uj5u.com熱心網友回復:
原因是您沒有正確分配第二個資料庫。您還需要為第二個資料庫設定正確的配置
$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...
uj5u.com熱心網友回復:
我沒有使用 Codeigniter 的經驗,但是在標準 sql 查詢中,您可以在表前添加資料庫名稱以從另一個資料庫獲取資訊,例如:
從 sakila.actor 中選擇 *;
假設您沒有連接到 sakila db。
使用這種方法,兩個資料庫必須具有相同的憑據
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/514622.html
標籤:mysql代码点火器
