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

PHP MSSQL 操作類完整封裝:連線、CRUD、交易與錯誤處理

     編輯:PHP 綜合知識

類別架構概覽

class MSSql {
    private $link;
    private $queryCount = 0;

    // 連線
    public function connect($host, $user, $pass, $db) { ... }

    // 執行 SQL
    public function query($sql) { ... }

    // 插入並回傳自增 ID
    public function insert($table, array $data) { ... }

    // 更新並回傳影響行數
    public function update($table, array $data, $where = '') { ... }

    // 刪除並回傳影響行數
    public function delete($table, $where = '') { ... }

    // 工具:值跳脫/還原
    public function encode($str) { ... }
    public function decode($str) { ... }

    // 內部:建構 INSERT/UPDATE 片段
    private function buildInsert(array $data) { ... }
    private function buildUpdate(array $data) { ... }

    // 資源釋放
    public function free($result) { ... }
    public function close() { ... }
}

核心方法實作精華

// 插入:使用 SCOPE_IDENTITY() 取得自增 ID
public function insert($table, array $data) {
    $sql = "INSERT INTO $table " . $this->buildInsert($data) .
           "; SELECT SCOPE_IDENTITY() AS insertid";
    $row = $this->fetchRow($this->query($sql));
    $this->free($result);
    return $row['insertid'];
}

// 更新:使用 @@ROWCOUNT 取得影響行數
public function update($table, array $data, $where = '') {
    $sql = "UPDATE $table SET " . $this->buildUpdate($data);
    if ($where) $sql .= " WHERE $where";
    $sql .= "; SELECT @@ROWCOUNT AS rowcount";
    $row = $this->fetchRow($this->query($sql));
    $this->free($result);
    return $row['rowcount'];
}

// 值跳脫:單引號雙寫
public function encode($str) {
    return str_replace("'", "''", $str);
}

使用範例

$db = new MSSql();
$db->connect('127.0.0.1', 'sa', 'password', 'mydb');

// 新增
$id = $db->insert('users', [
    'name' => "O'Reilly",
    'email' => 'test@example.com',
    'created' => date('Y-m-d H:i:s')
]);

// 修改
$db->update('users', ['name' => 'New Name'], "id = $id");

// 查詢
$res = $db->query("SELECT * FROM users WHERE id = $id");
$user = $db->fetchRow($res);
$db->free($res);

$db->close();

安全與效能注意事項

議題建議
SQL 注入所有值經 encode(),識別子 (表/欄) 用 [] 包裹
參數化查詢本類別未實作 prepared statement,高風險場景請自行擴充
連線池PHP 預設無連線池,考慮 oci_pconnect 模式或外部池化中介軟體
錯誤處理halt() 直接 exit,生產環境建議改拋出例外

現代替代方案

  • PDO_SQLSRV / PDO_DBLIB:跨平台、支援參數綁定、PHP 7+ 首選
  • Doctrine DBAL:抽象層、QueryBuilder、Schema 管理
  • Laravel Eloquent / Symfony Doctrine:完整 ORM 生態

相關專題

  • 《PHP 基於 PDO 操作資料庫技巧總結》
  • 《PHP + MongoDB 資料庫操作技巧大全》
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved