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

PHP MySQL CRUD 工具類封裝:DBUtils 單例模式實現增刪改查通用方法

     編輯:MySQL 綜合教學

PHP MySQL CRUD 工具類封裝:DBUtils 單例模式實現增刪改查通用方法

早期 PHP 專案常使用 mysql_* 系列函數(已棄用/移除),本文展示一個輕量級 DBUtils 類,封裝連接管理、編碼設定、查詢/更新通用方法,適合維護舊專案或快速原型開發。

完整類別碼

<?php
header("content-type:text/html;charset=utf-8");

class DBUtils {
    // 單例實例
    private static $instance = null;

    private function __construct() {}

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // 獲取連接(建議改用 mysqli/PDO)
    private function getConn() {
        $link = mysql_connect('127.0.0.1', 'root', '');
        mysql_query("SET NAMES utf8");
        mysql_select_db("news");
        return $link;
    }

    /**
     * 通用更新操作:INSERT / UPDATE / DELETE
     * @param string $sql
     * @return bool 影響行數 > 0 返回 true
     */
    public function update($sql) {
        $link = $this->getConn();
        mysql_query($sql);
        if (defined('DEBUG') && DEBUG) echo mysql_error();
        $affected = mysql_affected_rows($link);
        mysql_close($link);
        return $affected > 0;
    }

    /**
     * 通用查詢:返回多行陣列
     * @param string $sql
     * @return array
     */
    public function queryRows($sql) {
        $link = $this->getConn();
        $result = mysql_query($sql);
        if (defined('DEBUG') && DEBUG) echo mysql_error();
        $rows = [];
        while ($row = mysql_fetch_array($result)) {
            $rows[] = $row;
        }
        mysql_close($link);
        return $rows;
    }

    /**
     * 查詢單行
     * @param string $sql
     * @return array|false
     */
    public function queryRow($sql) {
        $rows = $this->queryRows($sql);
        return !empty($rows[0]) ? $rows[0] : false;
    }

    /**
     * 查詢單值(如 COUNT(*))
     * @param string $sql
     * @return mixed|false
     */
    public function queryObj($sql) {
        $rows = $this->queryRows($sql);
        return !empty($rows[0][0]) ? $rows[0][0] : false;
    }
}

使用範例

$db = DBUtils::getInstance();

// 更新
$db->update("INSERT INTO users(name, email) VALUES('張三', 'zhang@example.com')");

// 多行查詢
$users = $db->queryRows("SELECT * FROM users WHERE status = 1");

// 單行查詢
$user = $db->queryRow("SELECT * FROM users WHERE id = 100");

// 單值查詢
$count = $db->queryObj("SELECT COUNT(*) FROM users");

⚠️ 重要遷移提醒

  • mysql_* 函數 PHP 5.5 棄用、PHP 7.0 移除
  • 新專案**強制使用 mysqli 或 PDO**
  • 遷移重點:
    • 預處理語句防注入
    • 物件導向 API
    • 支援事務、預處理、多結果集

PDO 版本速寫參考

class PdoUtils {
    private static $pdo = null;
    private function __construct() {}
    public static function getInstance() {
        if (self::$pdo === null) {
            self::$pdo = new PDO("mysql:host=127.0.0.1;dbname=news;charset=utf8", 'root', '', [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);
        }
        return self::$pdo;
    }
}

// 使用
$pdo = PdoUtils::getInstance();
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([100]);
$user = $stmt->fetch();

儘早遷移至 PDO/mysqli,享受安全、效能、可維護性紅利。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved