類別架構概覽
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 資料庫操作技巧大全》