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

PHP 封裝 MySQL 連線類別實作與用法解析

     編輯:PHP 綜合知識

在早期的 PHP 開發中,開發者常將資料庫連線邏輯封裝成類別,以便重複使用並簡化操作。本文透過一個具體範例,示範如何建立一個封裝 MySQL 連線、查詢與結果處理的 PHP 類別,並說明其核心方法的運作方式。

類別結構設計

該 mysql 類別包含資料庫連線參數(主機、使用者、密碼、資料庫名稱)、連線資源、查詢語句、結果集與資料陣列等私有屬性。建構子負責初始化參數並自動建立連線與選擇資料庫。

核心方法說明

  • db_connect():使用 mysql_connect 建立連線,失敗時終止腳本並輸出錯誤訊息。
  • selectdb():透過 mysql_select_db 選擇指定資料庫。
  • query():執行 SQL 查詢並回傳結果資源。
  • get_result($sql):執行查詢並將結果集逐行轉換為關聯陣列,最終回傳包含所有資料列的二維陣列。
  • get_num():取得結果集的列數。

程式碼範例

class mysql {
    private $db_name;
    private $db_host;
    private $db_user;
    private $db_pwd;
    private $conn;
    private $querysql;
    private $result;
    private $resultarray = array();
    private $row;

    // 建構子:初始化參數並自動連線
    public function __construct($dbname, $dbhost, $dbuser, $dbpwd) {
        $this->db_name = $dbname;
        $this->db_host = $dbhost;
        $this->db_pwd  = $dbpwd;
        $this->db_user = $dbuser;
        $this->db_connect();
        $this->selectdb();
    }

    // 連線資料庫
    private function db_connect() {
        $this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd)
            or die("Could not Connect MySql Server");
    }

    // 選擇資料庫
    private function selectdb() {
        mysql_select_db($this->db_name) or die("unable to select dbname");
    }

    // 執行查詢
    private function query() {
        return $this->result = mysql_query($this->querysql);
    }

    // 取得查詢結果陣列
    public function get_result($sql) {
        $this->querysql = $sql;
        $this->query();
        if ($this->get_num() > 0) {
            while ($this->row = mysql_fetch_array($this->result)) {
                $this->resultarray[] = $this->row;
            }
            return $this->resultarray;
        }
        return false;
    }

    // 取得資料筆數
    private function get_num() {
        return $this->num = mysql_num_rows($this->result);
    }
}

// 使用範例
$m = new mysql("testuser", "localhost", "root", "root");
$arrResult = $m->get_result("SELECT * FROM userinfo");
print_r($arrResult);

注意事項與現代化建議

上述範例使用已棄用的 mysql_* 函式(PHP 5.5.0 棄用,PHP 7.0.0 移除)。現代專案強烈建議改用 MySQLi 或 PDO,兩者皆支援預處理語句,能有效防止 SQL 注入,並提供物件導向介面。若維護舊專案,可考慮撰寫相容層或逐步重構。

本文提供的封裝思路仍具參考價值:將連線細節隱藏、統一錯誤處理、回傳標準化資料結構,是資料存取層設計的基礎模式。

  1. 上一篇文章:
  2. 下一篇文章:
PHP 擷取遠端網頁 標籤內容範例</a> <a href='https://code.yunyiwangluo.com/bianchen/phpzh/57243.html' target="_blank">PHP Cookie 機制深度解析:運作原理、設定讀取刪除與安全最佳實務</a> <a href='https://code.yunyiwangluo.com/bianchen/phpzh/67017.html' target="_blank">Linux 下開發 PHP C 擴展完整步驟指南</a> <a href='https://code.yunyiwangluo.com/bianchen/phpzh/68707.html' target="_blank">PHP GD 繪圖顯示中文字:UTF-8 編碼與 TrueType 字體實作</a> <a href='https://code.yunyiwangluo.com/bianchen/phpzh/63482.html' target="_blank">PHP 獲取指定日期所在月份首尾日期:高性能工具函數實現與邊界情況處理</a> <a href='https://code.yunyiwangluo.com/bianchen/phpzh/109533.html' target="_blank">PHP 建立 RSS 閱讀器入門:解析 XML 頻道與資料庫快取優化</a> <a href='https://code.yunyiwangluo.com/bianchen/phpzh/62673.html' target="_blank">PHP 判斷指定時間區間的三種實用方法</a> </div> </div> <div class="eqibneb bg1 mt20"> <div class="lkebxsg">欄目導航</div> <div class="eqibneb_1 ovv_hex"> <li><a class='childclass' href='https://code.yunyiwangluo.com/bianchen/phpjc/' target="_self">PHP 基礎</a></li> <li><a class='childclass' href='https://code.yunyiwangluo.com/bianchen/phpzh/' target="_self">PHP 綜合知識</a></li> <li><a class='childclass' href='https://code.yunyiwangluo.com/bianchen/phprm/' target="_self">PHP 入門</a></li> <li><a class='childclass' href='https://code.yunyiwangluo.com/bianchen/gyphp/' target="_self">PHP 相關知識</a></li> </div> </div> </div> <div class="qcxs_ie_he"></div> </div> </div> <div class="qcxs_ie_he"></div> <div class="ebrxbsbf">Copyright © <a href="https://code.yunyiwangluo.com/" target="_blank" title="程式碼之家">程式碼之家</a> All Rights Reserved </div> </body> </html>