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

PHP MySQL 資料庫封裝類別範例

     編輯:PHP 綜合知識

簡易 Mysql 類別(教學用,生產請用 PDO)

<?php
class Mysql {
    private $host = 'localhost';
    private $user = 'root';
    private $pwd  = 'root';
    private $dbName = 'test';
    private $charset = 'utf8';
    private $conn = null;

    public function __construct() {
        $this->connect();
        $this->switchDb($this->dbName);
        $this->setChar($this->charset);
    }

    private function connect() {
        $this->conn = mysql_connect($this->host, $this->user, $this->pwd);
        if (!$this->conn) die('DB連線失敗: ' . mysql_error());
    }

    public function switchDb($db) {
        mysql_select_db($db, $this->conn) or die('選擇資料庫失敗');
    }

    public function setChar($charset) {
        mysql_query("SET NAMES $charset", $this->conn);
    }

    public function query($sql) {
        return mysql_query($sql, $this->conn);
    }

    public function getAll($sql) {
        $res = $this->query($sql);
        if (!$res) return false;
        $list = [];
        while ($row = mysql_fetch_assoc($res)) $list[] = $row;
        return $list;
    }

    public function getRow($sql) {
        $res = $this->query($sql);
        return $res ? mysql_fetch_assoc($res) : false;
    }

    public function getOne($sql) {
        $res = $this->query($sql);
        if (!$res) return false;
        $row = mysql_fetch_row($res);
        return $row[0] ?? false;
    }

    public function close() {
        mysql_close($this->conn);
    }
}

// 使用範例
$mysql = new Mysql();
$mysql->query("INSERT INTO stu VALUES (4, 'wangwu', '99998')");
$rows = $mysql->getAll("SELECT * FROM stu");
print_r($rows);

關鍵方法說明

方法用途回傳值
query()執行任意 SQL資源/布林
getAll()查詢多筆二維陣列
getRow()查詢單筆關聯陣列
getOne()查詢單一欄位值純量/false

⚠️ 重要提醒

  • mysql_* 函式已於 PHP 7.0 移除,僅供維護舊專案參考。
  • 新專案請使用 PDO 或 MySQLi,支援預處理語句、交易、物件導向介面。
  • PDO 範例:
    $pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8", 'root', 'root');
    $stmt = $pdo->prepare("SELECT * FROM stu WHERE id = ?");
    $stmt->execute([4]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved