ERRMODE_EXCEPTION 統一錯誤處理INSERT INTO ... SET col=val 避免字段值順序錯位query()/fetchAll() 等原生方法<?php
class HRDB {
protected $pdo, $res, $config;
public function __construct($config) {
$this->config = $config;
$this->connect();
}
protected function connect() {
$this->pdo = new PDO(
$this->config['dsn'],
$this->config['name'],
$this->config['password']
);
$this->pdo->query('SET NAMES utf8');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function close() { $this->pdo = null; }
// 通用查詢/執行/獲取方法
public function query($sql) { $this->res = $this->pdo->query($sql); }
public function exec($sql) { $this->res = $this->pdo->exec($sql); }
public function fetchAll() { return $this->res->fetchAll(); }
public function fetch() { return $this->res->fetch(); }
public function fetchColumn(){ return $this->res->fetchColumn(); }
public function lastInsertId(){ return $this->pdo->lastInsertId(); }
// 核心 CRUD 方法:select/insert/update/delete
// 統一參數:$debug(0/1/2), $mode, $table, $fields/$set, $where, $orderby
// 詳見下方完整實現...
}
// 字符串模式
$db->select(0, 0, 'tb_member', 'username,password', 'type=1 AND username LIKE "%os%"');
// 數組模式(自動拼接 AND)
$fields = ['username', 'password'];
$where = ['type = 1', 'username LIKE "%os%"'];
$db->select(0, 0, 'tb_member', $fields, $where);
// $mode: 0=多行, 1=單行, 2=計數
// $debug: 1=輸出SQL, 2=輸出SQL並exit
// 傳統 VALUES 寫法易漏字段/順序錯
// INSERT INTO tb (a,b,c) VALUES (1,2,3)
// 本類採用 SET 寫法(MySQL 專有,清晰對應)
$db->insert(0, 2, 'tb_member', 'username="test", type=1, dt=NOW()'); // 返回 lastInsertId
$db->insert(0, 2, 'tb_member', ['username="test"', 'type=1', 'dt=NOW()']); // 數組模式
$set = ['username="123"', 'type=1'];
$where = ['tbid=1', 'status=0'];
$db->update(0, 1, 'tb_member', $set, $where); // 返回影響行數
$db->delete(0, 1, 'tb_member', $where);
$db->query('SELECT username, password FROM tb_member WHERE id > ?', [100]);
$rows = $db->fetchAll(); // 完全兼容 PDO 預處理
$db1 = new HRDB([
'dsn' => 'mysql:host=localhost;dbname=db1',
'name' => 'root', 'password' => 'pwd1'
]);
$db2 = new HRDB([
'dsn' => 'mysql:host=192.168.1.2;dbname=db2',
'name' => 'user', 'password' => 'pwd2'
]);
// 同時操作兩個數據庫,數據遷移/同步極其方便
require_once 'HRDB.class.php';
$db = new HRDB($config);
echo "<hr><b>SELECT 測試</b><hr>";
$rs = $db->select(1, 0, 'tb_member', 'username,password', 'type=1');
echo "<hr><b>INSERT 測試</b></hr>";
$db->insert(1, 0, 'tb_member', 'username="test", type=1');
echo "<hr><b>自定義 SQL</b></hr>";
$db->query('SELECT * FROM tb_member LIMIT 5');
var_dump($db->fetchAll());
$db->close();
從舊版 mysql_* 函數遷移時,只需將連接配置改為 DSN 格式,SQL 寫法基本不變(INSERT SET 語法除外),大幅降低遷移成本。
作者:胡睿 (hooray0905@foxmail.com),2012-07-21 發布。