本類別封裝 mysql_* 擴充函式,提供連線管理、CRUD 簡化方法、資料庫/資料表清單查詢、多種擷取模式等功能。注意: mysql_* 函式自 PHP 5.5 棄用、PHP 7.0 移除,生產環境請改用 PDO 或 mysqli;本文僅供維護舊專案或教學參考。
class Mysql {
private $host, $user, $pass, $db, $conn, $result, $sql, $prefix, $charset;
public function __construct($host, $user, $pass, $db, $conn, $prefix, $charset) {
$this->host = $host; $this->user = $user; $this->pass = $pass;
$this->db = $db; $this->conn = $conn; $this->prefix = $prefix; $this->charset = $charset;
$this->connect();
}
private function connect() {
$this->conn = @mysql_connect($this->host, $this->user, $this->pass)
or die($this->showError("資料庫連線失敗,請檢查設定!"));
mysql_select_db($this->db, $this->conn) or die("找不到資料庫:{$this->db}");
$this->query("SET NAMES {$this->charset}");
}
}
public function query($sql) {
if (empty($sql)) $this->showError("SQL 不可為空!");
$this->sql = $sql;
return $this->result = mysql_query($sql, $this->conn);
}
public function insert($table, array $data) {
$table = $this->fullTableName($table);
$fields = implode('`, `', array_keys($data));
$values = "'" . implode("', '", array_map([$this, 'escape'], $data)) . "'";
return $this->query("INSERT INTO `{$table}` (`{$fields}`) VALUES ({$values})");
}
public function update($table, array $data, $where) {
$table = $this->fullTableName($table);
$set = [];
foreach ($data as $k => $v) $set[] = "`{$k}` = '" . $this->escape($v) . "'";
return $this->query("UPDATE `{$table}` SET " . implode(', ', $set) . " WHERE {$where}");
}
public function delete($table, $where) {
if (empty($where)) $this->showError("刪除條件不可為空!");
return $this->query("DELETE FROM `{$this->fullTableName($table)}` WHERE {$where}");
}
public function select($table, $columns = '*', $condition = '') {
return $this->query("SELECT {$columns} FROM `{$this->fullTableName($table)}` {$condition}");
}
public function findAll($table) { return $this->select($table); }
public function fetchArray() { return @mysql_fetch_array($this->result); } // 索引+關聯
public function fetchAssoc() { return @mysql_fetch_assoc($this->result); } // 關聯
public function fetchRow() { return @mysql_fetch_row($this->result); } // 數字索引
public function fetchObject() { return @mysql_fetch_object($this->result); } // 物件
insertId() — 取得最後 AUTO_INCREMENT IDfullTableName($t) — 自動加上表前綴showDatabases()、showTables($db) — 列舉資料庫/資料表numFields($table) — 顯示欄位定義escape() 方法(需實作 mysql_real_escape_string),所有外部輸入必須經過轉義。die() 洩露 SQL 細節;改用例外、日誌記錄、友善訊息。@ 抑制錯誤訊息會隱藏除錯線索,建議移除並統一例外處理。.env)。class PdoWrapper {
private $pdo;
public function __construct($dsn, $user, $pass) {
$this->pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
}
public function query($sql, array $params = []) {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
// fetchAll(), fetch(), lastInsertId() 等直接代理 $stmt
}
採用現代資料庫存取層,不僅修補安全漏洞,更能獲得效能優化、可測試性與長期維護性。