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

CodeIgniter 資料庫優化寫法總結:連線、查詢、CRUD 與進階技巧

     編輯:PHP 相關知識

資料庫連線管理

// 單一連線(自動連線設定於 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();            // 最後影響列數

效能調優建議

  1. 只選需要欄位:避免 SELECT *,使用 select('id, title')。
  2. 善用索引:where、join、order_by 欄位建立索引。
  3. 分頁優化:大資料量避免 OFFSET 深分頁,改用游標式分頁(WHERE id > $lastId LIMIT 20)。
  4. 啟用查詢快取:$this->db->cache_on() / cache_off() 控制特定查詢快取。
  5. 批次操作:大量寫入使用 insert_batch、update_batch。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved