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

PHP連接SQL Server通用類封裝:mssql擴展版資源管理與錯誤處理

     編輯:PHP 相關知識

類設計目標

  • 封裝連接/查詢/錯誤/資源釋放
  • 支持SELECT/INSERT/UPDATE/DELETE
  • 提供行遍歷、影響行數、錯誤信息

完整類代碼


Database error: %s
\n", $msg); printf("mssql Error: %s (%s)
\n", $this->Errno, $this->Error); die('Session halted.'); } function Connect() { if ($this->Link_ID == 0) { $this->Link_ID = @mssql_connect($this->Host, $this->User, $this->Password); if (!$this->Link_ID) $this->Halt('mssql_connect failed'); if (!@mssql_select_db($this->Database, $this->Link_ID)) { $this->Halt('mssql_select_db failed'); } } } function Close() { if ($this->Link_ID != 0) { @mssql_close($this->Link_ID); $this->Link_ID = 0; } } function Query($sql) { $this->Connect(); $this->Query_ID = @mssql_query($sql, $this->Link_ID); $this->Row = 0; if (!$this->Query_ID) { $this->Errno = mssql_errno($this->Link_ID); $this->Error = mssql_error($this->Link_ID); $this->Halt('Query failed: ' . $sql); } return $this->Query_ID; } function NextRecord() { if ($this->Query_ID) { $this->Row = @mssql_fetch_array($this->Query_ID); return $this->Row; } return false; } function AffectedRows() { return @mssql_rows_affected($this->Link_ID); } } ?>

使用示例


$db = new DB();
$db->Query("SELECT * FROM users WHERE status = 1");
while ($row = $db->NextRecord()) {
  echo $row['username'] . '
'; } $db->Close();

現代化遷移建議

  • mssql_*擴展PHP 7.0+已移除
  • 遷移至PDO_SQLSRV (Microsoft官方驅動) 或 PDO_ODBC
  • 類結構保持,底層替換為PDO方法
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved