mysql 類別封裝了資料庫連線、查詢執行、結果集處理、寫入更新刪除、結構描述管理等核心功能,內建 SQL 注入過濾與 XSS 防護,適合中小型專案快速開發。
function __construct($host, $user, $pwd, $db, $pconnect=false, $charset='utf8') {
$this->pconnect = $pconnect;
$this->dblink = $pconnect
? mysql_pconnect($host, $user, $pwd)
: mysql_connect($host, $user, $pwd);
if (!$this->dblink) fatal_error("連線失敗!");
mysql_unbuffered_query("SET NAMES {$charset}");
// MySQL 5.0.1+ 關閉嚴格模式避免 GROUP BY 報錯
if ($this->version() > '5.0.1') {
mysql_unbuffered_query("SET SQL_MODE = ''");
}
mysql_select_db($db) or fatal_error("選擇資料庫失敗!");
}
注意:mysql_* 函數自 PHP 5.5 棄用,PHP 7.0 移除。現代專案請改用 mysqli 或 PDO。
private $search = [
'/union\s*(/\*.*\*/)?\s*select/i',
'/load_file\s*(/\*.*\*/)?\s*\(/i',
'/into\s*(/\*.*\*/)?\s*outfile/i'
];
private $replace = ['union select', 'load_file (', 'into outfile'];
function escape($str) {
if (!is_array($str)) {
$str = preg_replace($this->search, $this->replace, $str);
return get_magic_quotes_gpc()
? $str
: mysql_real_escape_string($str, $this->dblink);
}
foreach ($str as $k => $v) $str[$k] = $this->escape($v);
return $str;
}
mysql_real_escape_string 雙重防護寫入/更新前自動檢查欄位是否存在於資料表,防止惡意欄位注入:
function insert($table, $data, $replace=false) {
$data = $this->escape($data);
$fields = $this->get_fields($table); // 獲取真實欄位列表
foreach ($data as $k => $v) {
if (in_array($k, $fields)) { // 只處理合法欄位
$flds[] = "`$k`";
$vals[] = is_string($v) ? "'$v'" : $v;
}
}
// ... 組裝 SQL 執行
}
function get_fields($table) {
$res = $this->fetch_all("SHOW COLUMNS FROM `{$table}`");
return array_column($res, 'Field');
}
| 方法 | 用途 | 特色 |
|---|---|---|
query($sql, $unbuffered) | 執行任意 SQL | 支援無緩衝查詢大結果集 |
fetch_one($sql) | 單行關聯陣列 | 自動過濾 XSS、轉義還原 |
fetch_all($sql) | 全部結果集 | 釋放資源、統一後處理 |
fetch_all_withkey($sql, $key) | 以指定欄位為鍵 | 適合字典/映射表快速查找 |
insert($table, $data, $replace) | 新增/覆蓋 | 欄位驗證、自動回傳自增 ID |
update($table, $data, $where) | 條件更新 | 欄位驗證、支援無 WHERE 全表替換 |
mysql_delete($table, $ids, $field) | 單/批量刪除 | 支援陣列 ID 與單一值 |
// 所有表狀態(大小、行數、引擎、編碼...)
function get_table_status($db) {
return $this->fetch_all("SHOW TABLE STATUS FROM `{$db}`");
}
// 單表狀態
function get_one_table_status($table) {
return $this->fetch_one("SHOW TABLE STATUS LIKE '$table'");
}
// 建立內容模型表(含 contentid + content mediumtext)
function create_model_table($table) {
if (in_array($table, $this->get_tables())) return false;
return $this->query("CREATE TABLE `{$table}` (
`contentid` MEDIUMINT(8) NOT NULL,
`content` MEDIUMTEXT NOT NULL,
KEY (`contentid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8", true);
}
// 動態新增欄位
function create_fields($table, $field, $size=0, $type='varchar') {
$size = strtoupper($type) === 'VARCHAR' ? $size : 8;
$sql = $size
? "ALTER TABLE `{$table}` ADD `$field` {$type}({$size}) NOT NULL"
: "ALTER TABLE `{$table}` ADD `$field` MEDIUMTEXT NOT NULL";
return $this->query($sql, true);
}
function filter_pass($string, $allowedtags='', $disabledattrs=[...]) {
if (is_array($string)) {
return array_map([$this, 'filter_pass'], $string);
}
// 1. strip_tags 保留允許標籤
// 2. 移除危險屬性(onload, onclick, onmouseover... 100+ 事件屬性)
// 3. 移除 javascript: 協定、樣式表達式等
// 4. 正規化空白字元
return $cleaned;
}
允許標籤預設:html, embed, title, meta, body, a, p, br, hr, h1-h6, font, u, i, b, strong, div, span, ol, ul, li, img, table, tr, td, map
PDO 或 mysqli,啟用預處理語句這個類別展示了早期 PHP 開發者對安全與便利性的巧妙平衡。雖然底層驅動已過時,但「欄位白名單驗證」、「統一後處理管道」、「結構反射輔助」等設計思想在現代框架中依然閃光。