類設計目標
- 封裝連接/查詢/錯誤/資源釋放
- 支持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方法