簡易 Mysql 類別(教學用,生產請用 PDO)
<?php
class Mysql {
private $host = 'localhost';
private $user = 'root';
private $pwd = 'root';
private $dbName = 'test';
private $charset = 'utf8';
private $conn = null;
public function __construct() {
$this->connect();
$this->switchDb($this->dbName);
$this->setChar($this->charset);
}
private function connect() {
$this->conn = mysql_connect($this->host, $this->user, $this->pwd);
if (!$this->conn) die('DB連線失敗: ' . mysql_error());
}
public function switchDb($db) {
mysql_select_db($db, $this->conn) or die('選擇資料庫失敗');
}
public function setChar($charset) {
mysql_query("SET NAMES $charset", $this->conn);
}
public function query($sql) {
return mysql_query($sql, $this->conn);
}
public function getAll($sql) {
$res = $this->query($sql);
if (!$res) return false;
$list = [];
while ($row = mysql_fetch_assoc($res)) $list[] = $row;
return $list;
}
public function getRow($sql) {
$res = $this->query($sql);
return $res ? mysql_fetch_assoc($res) : false;
}
public function getOne($sql) {
$res = $this->query($sql);
if (!$res) return false;
$row = mysql_fetch_row($res);
return $row[0] ?? false;
}
public function close() {
mysql_close($this->conn);
}
}
// 使用範例
$mysql = new Mysql();
$mysql->query("INSERT INTO stu VALUES (4, 'wangwu', '99998')");
$rows = $mysql->getAll("SELECT * FROM stu");
print_r($rows);
關鍵方法說明
| 方法 | 用途 | 回傳值 |
| query() | 執行任意 SQL | 資源/布林 |
| getAll() | 查詢多筆 | 二維陣列 |
| getRow() | 查詢單筆 | 關聯陣列 |
| getOne() | 查詢單一欄位值 | 純量/false |
⚠️ 重要提醒