mysql_connect)與持久連線(mysql_pconnect)$debug),輸出 SQL 與錯誤資訊query、fetch_array/assoc/row/object、num_rows、insert_id、affected_rowsshow_tables、show_dbs、create_db、drop_db、drop_table 等管理功能free_result)class Mysql {
private $db_host, $db_user, $db_pass, $db_name, $db_charset, $conn;
public $debug = false;
private $query_id, $result, $num_rows, $insert_id;
function __construct($host, $user, $pass, $name, $charset, $conn_type) {
$this->db_host = $host; $this->db_user = $user; $this->db_pass = $pass;
$this->db_name = $name; $this->db_charset = $charset; $this->conn = $conn_type;
$this->connect();
}
function __destruct() { @mysql_close($this->conn); }
public function connect() {
$this->conn = ($this->conn == 'pconn')
? @mysql_pconnect($this->db_host, $this->db_user, $this->db_pass)
: @mysql_connect($this->db_host, $this->db_user, $this->db_pass);
if (!$this->conn) $this->show_error('連線失敗');
@mysql_select_db($this->db_name, $this->conn) or $this->show_error("資料庫 {$this->db_name} 不可用");
mysql_query("SET NAMES {$this->db_charset}");
return $this->conn;
}
public function query($sql) {
if ($this->query_id) $this->free_result();
$this->query_id = @mysql_query($sql, $this->conn);
if (!$this->query_id) $this->show_error("SQL 執行錯誤: $sql");
return $this->query_id;
}
public function fetch_array() { return $this->query_id ? mysql_fetch_array($this->query_id) : null; }
public function fetch_assoc() { return $this->query_id ? mysql_fetch_assoc($this->query_id) : null; }
public function fetch_row() { return $this->query_id ? mysql_fetch_row($this->query_id) : null; }
public function fetch_object(){ return $this->query_id ? mysql_fetch_object($this->query_id) : null; }
public function num_rows() { return $this->query_id ? mysql_num_rows($this->query_id) : 0; }
public function insert_id(){ return mysql_insert_id(); }
public function free_result() { @mysql_free_result($this->query_id); $this->query_id = 0; }
public function show_error($msg) {
if ($this->debug) echo "錯誤:$msg
返回:".mysql_error()."";
else echo "
出現錯誤!
";
}
// ... show_tables, show_dbs, create_db, drop_db, drop_table, get_info 等管理方法
}
$db = new Mysql('localhost', 'root', 'pwd', 'testdb', 'utf8', 'conn'); // 或 'pconn'
$db->debug = true; // 開啟除錯
$db->query("SELECT * FROM users WHERE id > 10");
while ($row = $db->fetch_assoc()) {
print_r($row);
}
$db->free_result();
同前一篇,基於已移除的 mysql_* 擴充套件。新專案請使用 mysqli 或 PDO 重寫,並善用預備語句防止 SQL 注入。