類別核心功能
- 支援一般/持久連線、自動重連(
goneaway 機制)。
- 查詢計數、歷史記錄、快取清理。
- 字元集自動設定(
SET NAMES、sql_mode)。
- 完整封裝
fetch_array、fetch_first、fetch_all、result_first 等常用方法。
關鍵程式碼片段
function connect($dbhost, $dbuser, $dbpw, $dbname='', $dbcharset='', $pconnect=0) {
$this->link = $pconnect
? mysql_pconnect($dbhost, $dbuser, $dbpw)
: mysql_connect($dbhost, $dbuser, $dbpw);
if ($this->version() > '4.1' && $dbcharset) {
mysql_query("SET character_set_connection=$dbcharset, character_set_results=$dbcharset, character_set_client=binary", $this->link);
}
if ($this->version() > '5.0.1') mysql_query("SET sql_mode=''", $this->link);
if ($dbname) mysql_select_db($dbname, $this->link);
}
function query($sql, $type='', $cachetime=false) {
$func = ($type=='unbuffered' && function_exists('mysql_unbuffered_query'))
? 'mysql_unbuffered_query' : 'mysql_query';
if (!($q = $func($sql, $this->link)) && $type!='silent') $this->halt('MySQL Query Error', $sql);
$this->querynum++; $this->histories[] = $sql;
return $q;
}
function halt($msg='', $sql='') {
$err = mysql_error(); $erno = mysql_errno();
if ($erno==2006 && $this->goneaway-- > 0) { // 連線中斷自動重連
$this->connect($this->dbhost, $this->dbuser, $this->dbpw, $this->dbname, $this->dbcharset, $this->pconnect, $this->tablepre, $this->time);
$this->query($sql);
} else {
exit("Error:$err
Errno:$erno
SQL:$sql");
}
}
現代化建議
- 移除
mysql_*,改用 mysqli 或 PDO。
- 保留「自動重連」邏輯:mysqli 可設定
MYSQLI_OPT_RECONNECT;PDO 需自行捕獲例外重試。
- 採用 PSR-4 自動載入、命名空間、型別提示、介面契約(
DatabaseInterface)。
- 查詢建構器(Query Builder)可進一步簡化 CRUD。