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

基於 PDO 的 MySQL 數據庫操作類:支持多連接、鏈式調用、數組參數與調試模式

     編輯:PHP 綜合知識

類設計亮點

  • PDO 原生異常模式:ERRMODE_EXCEPTION 統一錯誤處理
  • 多數據庫連接:實例化即連接,支持同時操作多個庫
  • 靈活參數綁定:字符串/數組雙模式傳參(表名、字段、條件、數據)
  • INSERT 語法優化:採用 INSERT INTO ... SET col=val 避免字段值順序錯位
  • 調試模式分級:0=正常,1=輸出 SQL,2=輸出 SQL 並終止
  • 原生 PDO 直通:保留 query()/fetchAll() 等原生方法

核心代碼結構

<?php
class HRDB {
    protected $pdo, $res, $config;

    public function __construct($config) {
        $this->config = $config;
        $this->connect();
    }

    protected function connect() {
        $this->pdo = new PDO(
            $this->config['dsn'],
            $this->config['name'],
            $this->config['password']
        );
        $this->pdo->query('SET NAMES utf8');
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function close() { $this->pdo = null; }

    // 通用查詢/執行/獲取方法
    public function query($sql) { $this->res = $this->pdo->query($sql); }
    public function exec($sql)  { $this->res = $this->pdo->exec($sql); }
    public function fetchAll()  { return $this->res->fetchAll(); }
    public function fetch()     { return $this->res->fetch(); }
    public function fetchColumn(){ return $this->res->fetchColumn(); }
    public function lastInsertId(){ return $this->pdo->lastInsertId(); }

    // 核心 CRUD 方法:select/insert/update/delete
    // 統一參數:$debug(0/1/2), $mode, $table, $fields/$set, $where, $orderby
    // 詳見下方完整實現...
}

關鍵方法詳解

select() - 靈活查詢

// 字符串模式
$db->select(0, 0, 'tb_member', 'username,password', 'type=1 AND username LIKE "%os%"');

// 數組模式(自動拼接 AND)
$fields = ['username', 'password'];
$where  = ['type = 1', 'username LIKE "%os%"'];
$db->select(0, 0, 'tb_member', $fields, $where);

// $mode: 0=多行, 1=單行, 2=計數
// $debug: 1=輸出SQL, 2=輸出SQL並exit

insert() - 使用 SET 語法避免順序錯誤

// 傳統 VALUES 寫法易漏字段/順序錯
// INSERT INTO tb (a,b,c) VALUES (1,2,3)

// 本類採用 SET 寫法(MySQL 專有,清晰對應)
$db->insert(0, 2, 'tb_member', 'username="test", type=1, dt=NOW()'); // 返回 lastInsertId
$db->insert(0, 2, 'tb_member', ['username="test"', 'type=1', 'dt=NOW()']); // 數組模式

update() / delete() - 數組條件自動拼接

$set = ['username="123"', 'type=1'];
$where = ['tbid=1', 'status=0'];
$db->update(0, 1, 'tb_member', $set, $where); // 返回影響行數
$db->delete(0, 1, 'tb_member', $where);

原生 SQL 直通

$db->query('SELECT username, password FROM tb_member WHERE id > ?', [100]);
$rows = $db->fetchAll(); // 完全兼容 PDO 預處理

多連接示例

$db1 = new HRDB([
    'dsn' => 'mysql:host=localhost;dbname=db1',
    'name' => 'root', 'password' => 'pwd1'
]);

$db2 = new HRDB([
    'dsn' => 'mysql:host=192.168.1.2;dbname=db2',
    'name' => 'user', 'password' => 'pwd2'
]);

// 同時操作兩個數據庫,數據遷移/同步極其方便

測試代碼片段

require_once 'HRDB.class.php';
$db = new HRDB($config);

echo "<hr><b>SELECT 測試</b><hr>";
$rs = $db->select(1, 0, 'tb_member', 'username,password', 'type=1');

echo "<hr><b>INSERT 測試</b></hr>";
$db->insert(1, 0, 'tb_member', 'username="test", type=1');

echo "<hr><b>自定義 SQL</b></hr>";
$db->query('SELECT * FROM tb_member LIMIT 5');
var_dump($db->fetchAll());

$db->close();

遷移指南

從舊版 mysql_* 函數遷移時,只需將連接配置改為 DSN 格式,SQL 寫法基本不變(INSERT SET 語法除外),大幅降低遷移成本。

作者:胡睿 (hooray0905@foxmail.com),2012-07-21 發布。

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