提供一款簡單實現的連接類是利用php 構造函數自動創建連接與刪除操作,有需要的朋友可以參考。 代碼如下 復制代碼
class mysql {
private $db_host; //數據庫主機
private $db_user; //數據庫用戶名
private $db_pwd; //數據庫用戶名密碼
private $db_database; //數據庫名
private $conn; //數據庫連接標識;
private $result; //執行query命令的結果資源標識
private $sql; //sql執行語句
private $row; //返回的條目數
private $coding; //數據庫編碼,GBK,UTF8,gb2312
private $bulletin = true; //是否開啟錯誤記錄
private $show_error = true; //測試階段,顯示所有錯誤,具有安全隱患,默認關閉
private $is_error = false; //發現錯誤是否立即終止,默認true,建議不啟用,因為當有問題時用戶什麼也看不到是很苦惱的
/*構造函數*/
public function __construct($db_host, $db_user, $db_pwd, $db_database, $conn, $coding) {
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pwd = $db_pwd;
$this->db_database = $db_database;
$this->conn = $conn;
$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) {
//調試中使用,sql語句出錯時會自動打印出來
if ($this->show_error) {
$this->show_error("錯誤SQL語句:", $this->sql);
}
} else {
$this->result = $result;
}
return $this->result;
}
/*創建添加新的數據庫*/
public function create_database($database_name) {
$database = $database_name;
$sqlDatabase = 'create database ' . $database;
$this->query($sqlDatabase);
}