查詢操作
| 方法 | 說明 | 回傳值 |
$this->db->query($sql) | 執行自訂 SQL | CI_DB_result 物件 |
$this->db->get('table') | SELECT * FROM table | CI_DB_result 物件 |
$this->db->get('table', 10, 20) | SELECT * FROM table LIMIT 20, 10 | CI_DB_result 物件 |
$this->db->get_where('table', ['id'=>$id], $offset) | 帶 WHERE 條件查詢 | CI_DB_result 物件 |
結果集處理
| 方法 | 說明 | 回傳型別 |
$query->result() | 所有列,物件陣列 | array of stdClass |
$query->result_array() | 所有列,關聯陣列 | array of array |
$query->row() | 第一列,物件 | stdClass / null |
$query->row_array() | 第一列,關聯陣列 | array / null |
$query->num_rows() | 結果列數 | int |
$query->num_fields() | 欄位數 | int |
$query->free_result() | 釋放記憶體 | void |
插入操作
$data = ['name' => $name, 'email' => $email, 'url' => $url];
$this->db->insert('table_name', $data); // 便捷插入
$this->db->insert_string('table_name', $data); // 回傳 SQL 字串
$insertId = $this->db->insert_id(); // 取得 AUTO_INCREMENT ID
$affected = $this->db->affected_rows(); // 影響列數
更新操作
$data = ['name' => $name, 'email' => $email];
$where = "author_id = 1 AND status = 'active'";
$this->db->update('table_name', $data, $where);
$this->db->update_string('table_name', $data, $where); // 回傳 SQL 字串
刪除操作
$this->db->delete('table_name', ['name' => $name]); // WHERE name = ...
$this->db->truncate('table_name'); // 清空資料表
查詢建構器
| 方法 | SQL 等價 |
$this->db->select('title, content, date') | SELECT title, content, date |
$this->db->select_max('age', 'nianling') | SELECT MAX(age) AS nianling |
$this->db->from('table_name') | FROM table_name |
$this->db->where('name', $name) | WHERE name = 'value' |
$this->db->where_in('id', [1,2,3]) | WHERE id IN (1,2,3) |
$this->db->like('title', 'match', 'both') | WHERE title LIKE '%match%' |
$this->db->or_like('title', 'match') | OR title LIKE '%match%' |
$this->db->group_by('category') | GROUP BY category |
$this->db->order_by('date', 'DESC') | ORDER BY date DESC |
$this->db->limit(10, 20) | LIMIT 20, 10 |
實用工具方法
$this->db->count_all('table_name'); // 資料表總列數
$this->db->last_query(); // 最後執行的 SQL 字串
$this->db->version(); // 資料庫版本
$this->db->platform(); // 資料庫平台
參數綁定(防止 SQL Injection)
$sql = "SELECT * FROM users WHERE id = ? AND status = ? AND role = ?";
$this->db->query($sql, [3, 'active', 'admin']);
事務控制
$this->db->trans_start();
$this->db->query('INSERT ...');
$this->db->query('UPDATE ...');
$this->db->trans_complete(); // 自動判斷 commit 或 rollback