CodeIgniter(CI)作為輕量級 PHP 框架,其資料庫類提供了優雅的 Active Record 模式與傳統查詢介面。本文以 PostgreSQL 為例,完整示範從建表、配置、連線到 CRUD 操作的全流程,適用於 CI 2.x/3.x 版本。
-- 建立資料庫與資料表
CREATE DATABASE test;
CREATE TABLE users(
id INT NOT NULL,
name VARCHAR(10),
pwd VARCHAR(10),
email VARCHAR(20)
);
-- 插入測試資料
INSERT INTO users VALUES(1,'shunping','shunping','aa@163.com');
INSERT INTO users VALUES(2,'shunping2','shunping2','bb@163.com');
編輯 application/config/database.php:
$active_group = "default"; $db['default']['hostname'] = "localhost"; $db['default']['username'] = "postgres"; $db['default']['password'] = "admin"; $db['default']['database'] = "test"; $db['default']['dbdriver'] = "postgre"; // PostgreSQL 驅動 $db['default']['dbprefix'] = ""; $db['default']['active_r'] = TRUE; // 啟用 Active Record $db['default']['pconnect'] = FALSE; // 非持久連線 $db['default']['db_debug'] = TRUE; // 開啟除錯 $db['default']['cache_on'] = FALSE; $db['default']['cachedir'] = ""; $db['default']['port'] = "5432"; // PostgreSQL 預設埠
mysql、mysqli、postgre、odbc、pdo 等$this->db->get() 等 Active Record 方法FALSE,避免連線洩漏建立 application/controllers/db1.php:
<?php
class Db1 extends Controller {
function index() {
// 載入資料庫類庫(自動讀取 config/database.php)
$this->load->database();
// 傳統 SQL 查詢
$query = $this->db->query("SELECT name, pwd, email FROM users");
// 遍歷結果(回傳物件陣列)
foreach ($query->result() as $row) {
echo $row->name;
echo $row->pwd;
echo $row->email . "<br>";
}
echo "Total Result==" . $query->num_rows();
}
}
?>
result():回傳物件陣列result_array():回傳關聯陣列row():單筆結果物件row_array():單筆關聯陣列num_rows():筆數訪問:https://localhost:8888/index.php/db1
正常應輸出兩筆使用者資料與總筆數。
php.ini 是否載入 extension=pdo_pgsql 或 extension=pgsqlpostgresql.conf 的 listen_addressespg_hba.conf 需允許該使用者從 localhost 連線// 插入
$data = array('name' => 'test', 'email' => 'test@example.com');
$this->db->insert('users', $data);
// 更新
$this->db->where('id', 1);
$this->db->update('users', array('name' => 'updated'));
// 刪除
$this->db->delete('users', array('id' => 2));
// 條件查詢
$this->db->select('name, email');
$this->db->from('users');
$this->db->where('id >', 0);
$this->db->order_by('id', 'DESC');
$query = $this->db->get();
CodeIgniter 資料庫類封裝良好,配置簡單且支援多種驅動。掌握 database.php 設定與 $this->db 核心方法,即可高效完成大多數資料操作需求。建議專案中統一使用 Active Record 模式,提升程式碼可讀性與安全性(自動跳脫)。