【PHP】MySQL 数据库操作类

时间:2022-12-11 11:46:35
<?php
/*
* Mysql 数据库操作类
*
* Author: DYmyw
* Email: dymayongwei@163.com
* Date: 2012/03/15
* Version: 1.0
*/
class Mysql{
private $host;// 数据库主机名
private $user;// 数据库用户名
private $password;// 数据库用户密码
private $database;// 数据库名
private $pconnect;// 永久连接标示符
private $conn;// 数据库连接标示符
private $result;// 执行 SQL 语句获取的结果资源集
private $result_arr = array();// 资源集数组
public$debug = 1;// 调试模式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();
}

}
}
?>