本類提供了豐富的數據庫操作方法,支持多種獲取結果集的方式,內建調試功能和錯誤處理機制。
class mysql {
private $db_host; // 主機地址
private $db_user; // 用戶名
private $db_pass; // 密碼
private $db_name; // 數據庫名
private $db_charset; // 編碼
private $conn; // 連接標識
public $debug = false; // 調試開關
private $query_id; // 查詢資源
private $result; // 結果集
private $num_rows; // 行數
private $insert_id; // 最後插入ID
}
function __construct($db_host, $db_user, $db_pass, $db_name, $db_charset, $conn) {
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_name = $db_name;
$this->db_charset = $db_charset;
$this->conn = $conn;
$this->connect();
}
public function connect() {
if ($this->conn == 'pconn') {
@$this->conn = mysql_pconnect($this->db_host, $this->db_user, $this->db_pass);
} else {
@$this->conn = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
}
if (!$this->conn) {
$this->show_error('數據庫連接失敗:用戶名或密碼錯誤!');
}
if (!@mysql_select_db($this->db_name, $this->conn)) {
$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 mysql_fetch_array($this->query_id); }
public function fetch_assoc() { return mysql_fetch_assoc($this->query_id); }
public function fetch_row() { return mysql_fetch_row($this->query_id); }
public function fetch_object() { return mysql_fetch_object($this->query_id); }
解決開發環境(本地)與生產環境(遠程)數據庫配置切換問題:
'localhost',
'db_user' => 'root',
'db_pass' => 'root',
'db_name' => 'test'
);
// 遠程數據庫配置
$mysql_remote_data = array(
'db_host' => '61.183.41.178',
'db_user' => 'xxx',
'db_pass' => 'xxx',
'db_name' => 'xxx'
);
// 公共配置
$tb_prefix = 'php95_';
$db_charset = 'utf-8';
$conn = ''; // 連接類型
// 自動檢測並連接
if (@mysql_connect($mysql_local_data['db_host'], $mysql_local_data['db_user'], $mysql_local_data['db_pass'])) {
$db = new mysql(
$mysql_local_data['db_host'],
$mysql_local_data['db_user'],
$mysql_local_data['db_pass'],
$mysql_local_data['db_name'],
$db_charset,
$conn
);
} else {
$db = new mysql(
$mysql_remote_data['db_host'],
$mysql_remote_data['db_user'],
$mysql_remote_data['db_pass'],
$mysql_remote_data['db_name'],
$db_charset,
$conn
);
}
$db->show_tables(); // 測試:顯示所有表名
?>
APP_ENV=production)