首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP MySQL 資料庫操作類(Discuz 風格)

     編輯:PHP 相關知識

類別核心功能

  • 支援一般/持久連線、自動重連(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"); } }

現代化建議

  1. 移除 mysql_*,改用 mysqli 或 PDO。
  2. 保留「自動重連」邏輯:mysqli 可設定 MYSQLI_OPT_RECONNECT;PDO 需自行捕獲例外重試。
  3. 採用 PSR-4 自動載入、命名空間、型別提示、介面契約(DatabaseInterface)。
  4. 查詢建構器(Query Builder)可進一步簡化 CRUD。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved