首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

CodeIgniter 資料庫操作優化寫法總整理

     編輯:PHP 綜合知識

整理 CodeIgniter 常用資料庫操作的優化寫法,涵蓋連線、查詢、新增、更新、刪除與輔助方法,幫助開發者寫出更簡潔、高效的程式碼。

資料庫連線

// 載入預設資料庫群組
$this->load->database();

// 手動連線多資料庫
$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

查詢操作

參數綁定查詢(防止 SQL 注入)

$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));

多筆結果查詢

// 自定義 SQL
$query = $this->db->query($sql);

// 便捷查詢:SELECT * FROM tablename
$query = $this->db->get('tablename');

// 分頁查詢:SELECT * FROM tablename LIMIT 20, 10
$query = $this->db->get('tablename', 10, 20);

// 結果處理
$query->result();        // 物件陣列
$query->result_array();  // 關聯陣列
$query->num_rows();      // 總筆數
$query->num_fields();    // 欄位數

// 單筆結果
$row = $query->row();        // 物件
$row = $query->row_array();  // 陣列

新增資料

$data = array(
    'title' => $title,
    'name'  => $name
);

$this->db->insert('tablename', $data);        // 便捷新增
$this->db->insert_string('tablename', $data); // 產生 INSERT 字串

// 取得剛新增的 ID 及影響行數
$insert_id = $this->db->insert_id();
$affected  = $this->db->affected_rows();

更新資料

$data = array(
    'name'  => $name,
    'email' => $email
);
$where = "id = 1";

$this->db->update('tablename', $data);
$this->db->update_string('tablename', $data, $where);

刪除資料

$array = array('name' => $name, 'title' => $title);
$this->db->delete('tablename', $array);  // 依條件刪除

$this->db->truncate('tablename');        // 清空資料表

常用輔助方法

// WHERE 條件陣列寫法
$array = array('name' => $name, 'title' => $title);
$this->db->where($array);  // WHERE name = '...' AND title = '...'

// 統計資料表總列數
$count = $this->db->count_all('tablename');

// 釋放查詢結果記憶體
$query->free_result();

最佳實踐建議

  • 善用 get()、get_where() 等 Active Record 方法,減少手寫 SQL。
  • 複雜查詢才使用 query() 搭配參數綁定。
  • 大量資料操作後記得呼叫 free_result() 釋放記憶體。
  • 交易處理請使用 $this->db->trans_start() / trans_complete()。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved