<?php
class Mysql{
private $host;
private $user;
private $password;
private $database;
private $pconnect;
private $conn;
private $result;
private $result_arr = array();
private debug = 1;
//构造函数,连接数据库
public function __construct($host='',$user='',$password='',$database='',$pconnect=false){
if($host!='') $this->host = $host;
if($user!='') $this->user = $user;
if($password!='') $this->password = $password;
if($database!='') $this->database = $database;
if(isset($pconnect))$this->pconnect = $pconnect;
if(!$this->conn){
if($this-<pconnect){
$this->conn = @mysql_pconnect($this->host,$this->user,$this->password);
}else{
$this->conn = @mysql_connect($this->host,$this->user.$this->password);
}
if(!$this->conn){
$this->db_error('连接数据库失败!','不能连接到指定数据库服务器,请稍后再试');
}
}
if(!$this->select_db($this->database)){
$this->db_error('打开数据库失败','不能打开制定的数据库,请检查数据库名再试');
}
return $this->conn;
}
//选择数据库
public function select_db($database){
return @mysql_select_db($database,$this->conn);
}
//设置字符集
public function set_charset($charset){
return $this->query("set names $charset");
}
//执行SQL语句
public function query($sql){
if($sql == '')
$this->db_error('SQL语句错误!','SQL语句不能为空!');
$this->result = @mysql_query($sql,$this->conn);
if(!$this->result)
$this->db_error('执行SQL语句失败!','错误的SQL语句:'.$sql);
array_push($this->result_arr,$this->result);
return $this->result;
}
//获取数据集记录数
public function num_rows($result){
return @mysql_num_rows($result);
}
//以关联数据的形式获取数据集
public function fetch_array($result){
return @mysql_fetch_array($result);
}
//获取上次INSERT操作后残生的ID
public function insert_id(){
return @mysql_insert_id($this->conn);
}
//析构函数,自动关闭数据库,垃圾回收
public function __destruct(){
if($this->result_arr && is_array($this->result_arr)){
foreach($this->result_arr as $key => $val){
@mysql_free_result($val);
}
}
if($this->conn) @mysql_close($this->conn);
}
//错误信息
public function db_error($error,$detail){
if($this->debug == 1){
$err_msg = '';
$err_msg .= '出现数据库错误:'.$error."\n";
$err_msg .= '数据库错误信息:'.$detail."\n";
$err_msg .= 'MySQL错误提示:'.$mysql_error()."\n";
$err_msg .= 'MySQL错误代码:'.$mysql_errno()."\n";
$err_msg .= '日期:'.date("l jS F Y H:i:s A")."\n";
$err_msg .= '脚步:'.$_SERVER['REQUEST_URI']."\n";
die("<!-- 错误信息:\n".$err_msg."-->");
}else{
die();
}
}
}
?>