類別結構
<?php
class MySQL {
// 設定屬性
public $DBServer = 'localhost';
public $DBName = '';
public $DBUser = '';
public $DBPass = '';
public $OnErrorResume = 1; // 1=關閉錯誤提示
// 內部狀態
private $LinkID = 0;
private $QueryID = 0;
public $ResultS = [];
public $Error = '';
// 連線
public function Connect($Srv = '', $Usr = '', $Pass = '', $DB = '') {
$Srv = $Srv ?: $this->DBServer;
$Usr = $Usr ?: $this->DBUser;
$Pass = $Pass ?: $this->DBPass;
$DB = $DB ?: $this->DBName;
if ($this->LinkID == 0) {
$this->LinkID = @mysql_connect($Srv, $Usr, $Pass)
or die('資料庫連線失敗,請聯繫管理員。');
}
@mysql_select_db($DB, $this->LinkID)
or die('資料庫選擇失敗,請聯繫管理員。');
return $this->LinkID;
}
// 釋放結果
public function Free() {
@mysql_free_result($this->QueryID);
$this->QueryID = 0;
}
// 記錄總數
public function RowS() {
if (!$this->QueryID) return 0;
return @mysql_num_rows($this->QueryID);
}
// 取得下一筆
public function NextRecord() {
if (!$this->QueryID) return 0;
$this->ResultS = @mysql_fetch_array($this->QueryID);
}
// 游標定位
public function Seek($seek) {
if (!$this->QueryID) return 0;
@mysql_data_seek($this->QueryID, $seek);
}
// 執行查詢
public function Query($Sql) {
if ($Sql == '') return 0;
if ($this->LinkID == 0) $this->Connect();
if ($this->QueryID) $this->Free();
$this->QueryID = @mysql_query($Sql, $this->LinkID);
$this->Error = mysql_error($this->LinkID);
if (!$this->QueryID) exit("$Sql 執行失敗.");
return $this->QueryID;
}
// 取得欄位值
public function GetRecord($Name) {
if (!$this->QueryID) return 0;
return $this->ResultS[$Name];
}
}
?>
使用範例
<?php
$db = new MySQL();
$db->DBName = 'mydb';
$db->DBUser = 'user';
$db->DBPass = 'pass';
$db->Connect();
$db->Query('SELECT * FROM users WHERE status = 1');
while ($db->NextRecord()) {
echo $db->GetRecord('username') . '
';
}
$db->Free();
?>
遷移至 mysqli/PDO 建議
- 將
mysql_* 全部替換為 mysqli_* 或 PDO 方法。
- 連線改用
new mysqli(...) 或 new PDO(...)。
- 查詢使用預處理
prepare()/execute()。
- 錯誤模式設為異常:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);。
- 移除
@ 抑制錯誤,改用 try-catch。