資料庫連線管理
// 單一連線(自動連線設定於 database.php)
$this->load->database();
// 手動連線
$this->load->database();
// 多資料庫連線
$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);
// 使用第二組連線
$DB1->query('SELECT * FROM table1');
$DB2->query('SELECT * FROM table2');
查詢優化寫法
參數綁定(安全、效能)
$sql = "SELECT * FROM articles WHERE category = ? AND status = ? AND author = ?";
$query = $this->db->query($sql, ['tech', 'published', 'john']);
便捷查詢方法
// 全表查詢
$query = $this->db->get('articles');
// 分頁查詢:LIMIT 20, 10(offset=20, limit=10)
$query = $this->db->get('articles', 10, 20);
// 條件查詢
$query = $this->db->get_where('articles', ['category' => 'tech'], 10);
結果處理最佳實務
// 物件陣列(適合屬性存取)
foreach ($query->result() as $row) {
echo $row->title;
}
// 關聯陣列(適合 JSON 輸出、陣列操作)
$data = $query->result_array();
// 單筆資料
$row = $query->row(); // 物件
$row = $query->row_array(); // 陣列
// 統計資訊
$total = $query->num_rows();
$fields = $query->num_fields();
// 釋放記憶體(大量資料查詢後建議呼叫)
$query->free_result();
寫入操作優化
批次插入(大量資料高效能)
$data = [
['title' => '文章1', 'content' => '...'],
['title' => '文章2', 'content' => '...'],
// ... 百筆以上
];
$this->db->insert_batch('articles', $data); // 單一 SQL 多值插入
插入/更新回傳資訊
$this->db->insert('articles', $data);
$newId = $this->db->insert_id(); // 新增 ID
$affected = $this->db->affected_rows(); // 影響列數
更新與刪除優化
$data = ['views' => $views + 1];
$this->db->where('id', $id);
$this->db->update('articles', $data);
// 刪除多條件
$conditions = ['status' => 'draft', 'author_id' => 5];
$this->db->delete('articles', $conditions);
// 清空資料表(重置 AUTO_INCREMENT)
$this->db->truncate('articles');
WHERE 條件進階用法
// 陣列條件 = AND 串接
$this->db->where(['name' => $name, 'title' => $title, 'status' => 'active']);
// IN / NOT IN
$this->db->where_in('category', ['tech', 'news', 'life']);
$this->db->where_not_in('id', [1, 2, 3]);
// LIKE 模糊搜尋
$this->db->like('title', 'keyword', 'both'); // %keyword%
$this->db->like('title', 'keyword', 'after'); // keyword%
$this->db->or_like('content', 'keyword'); // OR 條件
常用統計與除錯
$this->db->count_all('articles'); // 總筆數
$this->db->last_query(); // 除錯:最後 SQL
$this->db->insert_id(); // 最後插入 ID
$this->db->affected_rows(); // 最後影響列數
效能調優建議
- 只選需要欄位:避免
SELECT *,使用 select('id, title')。
- 善用索引:
where、join、order_by 欄位建立索引。
- 分頁優化:大資料量避免
OFFSET 深分頁,改用游標式分頁(WHERE id > $lastId LIMIT 20)。
- 啟用查詢快取:
$this->db->cache_on() / cache_off() 控制特定查詢快取。
- 批次操作:大量寫入使用
insert_batch、update_batch。