本文提供一個簡單的 PHP MySQL 資料庫連線類別範例,利用建構函數自動建立連線,並在解構時關閉連線。適合初學者參考學習物件導向資料庫操作的基本架構。
<?php
class MySQL {
private $db_host; // 資料庫主機
private $db_user; // 使用者名稱
private $db_pwd; // 密碼
private $db_database; // 資料庫名稱
private $conn; // 連線識別
private $result; // 查詢結果資源
private $sql; // SQL 執行語句
private $row; // 回傳筆數
private $coding; // 編碼 (GBK, UTF8, gb2312)
private $bulletin = true; // 是否記錄錯誤
private $show_error = true; // 測試階段顯示錯誤 (預設關閉,正式環境建議關閉)
private $is_error = false; // 發現錯誤是否立即終止
// 建構函數:自動連線
public function __construct($db_host, $db_user, $db_pwd, $db_database, $conn_type, $coding) {
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pwd = $db_pwd;
$this->db_database = $db_database;
$this->conn = $conn_type;
$this->coding = $coding;
$this->connect();
}
// 資料庫連線
public function connect() {
if ($this->conn == "pconn") {
// 永久連線
$this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd);
} else {
// 一般連線
$this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pwd);
}
if (!mysql_select_db($this->db_database, $this->conn)) {
if ($this->show_error) {
$this->show_error("資料庫不可用:", $this->db_database);
}
}
mysql_query("SET NAMES $this->coding");
}
// 執行 SQL 語句 (查詢、新增、修改、刪除)
public function query($sql) {
if ($sql == "") {
$this->show_error("SQL 語句錯誤:", "SQL 查詢語句為空");
}
$this->sql = $sql;
$result = mysql_query($this->sql, $this->conn);
if (!$result) {
if ($this->show_error) {
$this->show_error("錯誤 SQL 語句:", $this->sql);
}
} else {
$this->result = $result;
}
return $this->result;
}
// 建立新資料庫
public function create_database($database_name) {
$sqlDatabase = 'CREATE DATABASE ' . $database_name;
$this->query($sqlDatabase);
}
// 錯誤顯示輔助方法 (簡易實作)
private function show_error($msg1, $msg2) {
echo "Error: $msg1 $msg2
";
if ($this->is_error) exit;
}
}
?>
pconn 為永久連線,其他為一般連線) 及編碼。query() 方法執行任何 SQL 語句。$show_error 與 $is_error。重要: 本範例使用已棄用的 mysql_* 函式 (PHP 5.5.0 棄用,PHP 7.0.0 移除)。現代專案請改用 MySQLi 或 PDO,並採用預處理語句防止 SQL 注入。