PHP中对数据库操作的封装

   在动态网面设计中很多都要涉及到对数据库的操作,但是有时跟据需要而改用其它后台数据库,就需要大量修改程序。这是一件枯燥、费时而且容易出错的功作。其实我们可以用PHP中的类来实现对数据库操作的封装,从而使写出的程序在很小的改动下就可以完成后台数据库的更改。

<?
class dbInterface{ var $dbID=1; //用于确定当前操作的数据库,当dbID为1代表MySql,当为 2代表 SQL Server,为3时为ODBC或其它。
var $dbHost; //数据库所在主机域名
var $dbUsername; //数据库用户名
var $dbPassword; //用户密码
//设置主机、用户名及密码函数
function setParameter($host,$username,$password){
$this->dbUsername=$username;
$this->dbHost=$host;
$this->dbPassword=$password;

} //联接数库函数
function dbConnect(){
switch($this->dbID)
{
case 1;
return @mysql_connect($this->dbHost,$this->dbUsername,$this->dbPassword);
case 2;
//用支持SQL Server的函数
case 3;
//用支持ODBC的函数
}  
}
//关闭数库函数
function dbClose($dataHandle){
switch($this->dbID)
{
case 1;
mysql_close($dataHandle);
case 2;
//用支持SQL Server的函数
case 3;
//用支持ODBC的函数
}  
}

//执行SQL语句函数
function dbQuery($dbName,$sql,$dbHandle){
switch($this->dbID)
{
case 1;
return @mysql_db_query($dbName,$sql,$dbHandle);
case 2;
//用支持SQL Server的函数
case 3;
//用支持ODBC的函数
}  
}

//检索SQL返回值的当前记录函数
function dbFetchrow($dataHandle,$offset=-1){
switch($this->dbID)
{
case 1;
@mysql_data_seek($dataHandle,$offset);
return @mysql_fetch_row($dataHandle);
case 2;
//用支持SQL Server的函数
case 3;
//用支持ODBC的函数
}  
}

//返回检索记录数函数
function dbNumrows($dataHandle){
switch($this->dbID)
{
case 1;
return @mysql_num_rows($dataHandle);
case 2;
//用支持SQL Server的函数
case 3;
//用支持ODBC的函数
}  
}

//返回检索列数函数
function dbNumcols($dataHandle){
switch($this->dbID)
{
case 1;
return @mysql_num_fields($dataHandle);
case 2;
//用支持SQL Server的函数
case 3;
//用支持ODBC的函数
}  
}
}

 现把使用说明如下:

  在程序中用dbInterface类生一个对象$test=new dbInterface;

设置参数
test->$dbUsername ;用户名
test->$dbPassword;密码
test->$dbHost;主机
void setParameter(string host, string username, string password);

数据库连接:dbhandle test->dbConnect();

返回值:fasle ,数据库连接错误
>0, 数据库连接句柄

数据库关闭:void test->dbClose(dbhandle);

表操作:int test->dbQuery(string databasename, string sql,dbhandle);执行SQL语句

返回值: false, SQL执行错误
>0, SQL执行正确, 同时指向SQL返回值,

数据操作:int test->dbFetchrow(dataHandle,int offset);检索SQL返回值的当前记录,成功执行后,指针移向下一条记录
int test->dbNumrows(dataHandle); 取得SQL执行后(主要为SELECT语句)获得的记录数
int test->dbNumcols(dataHandle); 取得SQL执行后(主要为SELECT语句)获得的记录字段数

现在我们发一个例了讲解:

  数据库采用MQSQL:其主机名为 "localhost",用户名为"root"和密码""。

-----
<HTML><HEAD>
<TITLE>test</TITLE>
</HEAD><BODY>
<P> <?php
require("testdb.inc"); //装载dbInterface类
$test = new dbInterface;//用类dbInterface生成一个对象
$test->setParameter("localhost","root","");//设置数据库参数
$db = $test->dbConnect();//连接数据库
$Query = "SELECT name,pay FROM table ";//设置SQL语句
$temp_result = $test->dbQuery("testdb",$Query,$db);//执行数据主库操作
echo "<br>";
$ls_num = $test->dbNumrows($temp_result); //取得查询结果的记录数
echo $ls_num;
echo "<br>";
if (ls_num>0 )
{
$ls_col = $test->dbNumcols($db); //取得表的列数
echo $ls_col;  
echo "<br>";
$cate_result=$test->dbFetchrow($temp_result,0);//取得记录数的第一行
$hcid=$cate_result[0];// 取得name的值
$hcate=$cate_result[1];//取得pay的值
echo $hcid;
echo "<br>";
echo $hcate;
}

?>  
<HR>
<ADDRESS></ADDRESS>
</BODY></HTML> 


在mysql中有一个testdb数据库及其中的表table1,表包括:name和pay两个字段

php封装一个class类实现mysql数据库的增删该查

<?php
Class DB {
 
    private $link_id;
    private $handle;
    private $is_log;
    private $time;
 
    //构造函数
    public function __construct() {
        $this->time = $this->microtime_float();
        require_once("config.db.php");
        $this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
        $this->is_log = $db_config["log"];
        if($this->is_log){
            $handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");
            $this->handle=$handle;
        }
    }
     
    //数据库连接
    public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {
        if( $pconnect==0 ) {
            $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
            if(!$this->link_id){
                $this->halt("数据库连接失败");
            }
        } else {
            $this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
            if(!$this->link_id){
                $this->halt("数据库持久连接失败");
            }
        }
        if(!@mysql_select_db($dbname,$this->link_id)) {
            $this->halt('数据库选择失败');
        }
        @mysql_query("set names ".$charset);
    }
     
    //查询 
    public function query($sql) {
        $this->write_log("查询 ".$sql);
        $query = mysql_query($sql,$this->link_id);
        if(!$query) $this->halt('Query Error: ' . $sql);
        return $query;
    }
     
    //获取一条记录(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH)              
    public function get_one($sql,$result_type = MYSQL_ASSOC) {
        $query = $this->query($sql);
        $rt =& mysql_fetch_array($query,$result_type);
        $this->write_log("获取一条记录 ".$sql);
        return $rt;
    }
 
    //获取全部记录
    public function get_all($sql,$result_type = MYSQL_ASSOC) {
        $query = $this->query($sql);
        $i = 0;
        $rt = array();
        while($row =& mysql_fetch_array($query,$result_type)) {
            $rt[$i]=$row;
            $i++;
        }
        $this->write_log("获取全部记录 ".$sql);
        return $rt;
    }
     
    //插入
    public function insert($table,$dataArray) {
        $field = "";
        $value = "";
        if( !is_array($dataArray) || count($dataArray)<=0) {
            $this->halt('没有要插入的数据');
            return false;
        }
        while(list($key,$val)=each($dataArray)) {
            $field .="$key,";
            $value .="'$val',";
        }
        $field = substr( $field,0,-1);
        $value = substr( $value,0,-1);
        $sql = "insert into $table($field) values($value)";
        $this->write_log("插入 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //更新
    public function update( $table,$dataArray,$condition="") {
        if( !is_array($dataArray) || count($dataArray)<=0) {
            $this->halt('没有要更新的数据');
            return false;
        }
        $value = "";
        while( list($key,$val) = each($dataArray))
        $value .= "$key = '$val',";
        $value .= substr( $value,0,-1);
        $sql = "update $table set $value where 1=1 and $condition";
        $this->write_log("更新 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //删除
    public function delete( $table,$condition="") {
        if( empty($condition) ) {
            $this->halt('没有设置删除的条件');
            return false;
        }
        $sql = "delete from $table where 1=1 and $condition";
        $this->write_log("删除 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //返回结果集
    public function fetch_array($query, $result_type = MYSQL_ASSOC){
        $this->write_log("返回结果集");
        return mysql_fetch_array($query, $result_type);
    }
 
    //获取记录条数
    public function num_rows($results) {
        if(!is_bool($results)) {
            $num = mysql_num_rows($results);
            $this->write_log("获取的记录条数为".$num);
            return $num;
        } else {
            return 0;
        }
    }
 
    //释放结果集
    public function free_result() {
        $void = func_get_args();
        foreach($void as $query) {
            if(is_resource($query) && get_resource_type($query) === 'mysql result') {
                return mysql_free_result($query);
            }
        }
        $this->write_log("释放结果集");
    }
 
    //获取最后插入的id
    public function insert_id() {
        $id = mysql_insert_id($this->link_id);
        $this->write_log("最后插入的id为".$id);
        return $id;
    }
 
    //关闭数据库连接
    protected function close() {
        $this->write_log("已关闭数据库连接");
        return @mysql_close($this->link_id);
    }
 
    //错误提示
    private function halt($msg='') {
        $msg .= "
".mysql_error();
        $this->write_log($msg);
        die($msg);
    }
 
    //析构函数
    public function __destruct() {
        $this->free_result();
        $use_time = ($this-> microtime_float())-($this->time);
        $this->write_log("完成整个查询任务,所用时间为".$use_time);
        if($this->is_log){
            fclose($this->handle);
        }
    }
     
    //写入日志文件
    public function write_log($msg=''){
        if($this->is_log){
            $text = date("Y-m-d H:i:s")." ".$msg."
";
            fwrite($this->handle,$text);
        }
    }
     
    //获取毫秒数
    public function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}
 
?>
<?php
Class DB {
 
    private $link_id;
    private $handle;
    private $is_log;
    private $time;
 
    //构造函数
    public function __construct() {
        $this->time = $this->microtime_float();
        require_once("config.db.php");
        $this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]);
        $this->is_log = $db_config["log"];
        if($this->is_log){
            $handle = fopen($db_config["logfilepath"]."dblog.txt", "a+");
            $this->handle=$handle;
        }
    }
     
    //数据库连接
    public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0,$charset='utf8') {
        if( $pconnect==0 ) {
            $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
            if(!$this->link_id){
                $this->halt("数据库连接失败");
            }
        } else {
            $this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw);
            if(!$this->link_id){
                $this->halt("数据库持久连接失败");
            }
        }
        if(!@mysql_select_db($dbname,$this->link_id)) {
            $this->halt('数据库选择失败');
        }
        @mysql_query("set names ".$charset);
    }
     
    //查询 
    public function query($sql) {
        $this->write_log("查询 ".$sql);
        $query = mysql_query($sql,$this->link_id);
        if(!$query) $this->halt('Query Error: ' . $sql);
        return $query;
    }
     
    //获取一条记录(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH)              
    public function get_one($sql,$result_type = MYSQL_ASSOC) {
        $query = $this->query($sql);
        $rt =& mysql_fetch_array($query,$result_type);
        $this->write_log("获取一条记录 ".$sql);
        return $rt;
    }
 
    //获取全部记录
    public function get_all($sql,$result_type = MYSQL_ASSOC) {
        $query = $this->query($sql);
        $i = 0;
        $rt = array();
        while($row =& mysql_fetch_array($query,$result_type)) {
            $rt[$i]=$row;
            $i++;
        }
        $this->write_log("获取全部记录 ".$sql);
        return $rt;
    }
     
    //插入
    public function insert($table,$dataArray) {
        $field = "";
        $value = "";
        if( !is_array($dataArray) || count($dataArray)<=0) {
            $this->halt('没有要插入的数据');
            return false;
        }
        while(list($key,$val)=each($dataArray)) {
            $field .="$key,";
            $value .="'$val',";
        }
        $field = substr( $field,0,-1);
        $value = substr( $value,0,-1);
        $sql = "insert into $table($field) values($value)";
        $this->write_log("插入 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //更新
    public function update( $table,$dataArray,$condition="") {
        if( !is_array($dataArray) || count($dataArray)<=0) {
            $this->halt('没有要更新的数据');
            return false;
        }
        $value = "";
        while( list($key,$val) = each($dataArray))
        $value .= "$key = '$val',";
        $value .= substr( $value,0,-1);
        $sql = "update $table set $value where 1=1 and $condition";
        $this->write_log("更新 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //删除
    public function delete( $table,$condition="") {
        if( empty($condition) ) {
            $this->halt('没有设置删除的条件');
            return false;
        }
        $sql = "delete from $table where 1=1 and $condition";
        $this->write_log("删除 ".$sql);
        if(!$this->query($sql)) return false;
        return true;
    }
 
    //返回结果集
    public function fetch_array($query, $result_type = MYSQL_ASSOC){
        $this->write_log("返回结果集");
        return mysql_fetch_array($query, $result_type);
    }
 
    //获取记录条数
    public function num_rows($results) {
        if(!is_bool($results)) {
            $num = mysql_num_rows($results);
            $this->write_log("获取的记录条数为".$num);
            return $num;
        } else {
            return 0;
        }
    }
 
    //释放结果集
    public function free_result() {
        $void = func_get_args();
        foreach($void as $query) {
            if(is_resource($query) && get_resource_type($query) === 'mysql result') {
                return mysql_free_result($query);
            }
        }
        $this->write_log("释放结果集");
    }
 
    //获取最后插入的id
    public function insert_id() {
        $id = mysql_insert_id($this->link_id);
        $this->write_log("最后插入的id为".$id);
        return $id;
    }
 
    //关闭数据库连接
    protected function close() {
        $this->write_log("已关闭数据库连接");
        return @mysql_close($this->link_id);
    }
 
    //错误提示
    private function halt($msg='') {
        $msg .= "
".mysql_error();
        $this->write_log($msg);
        die($msg);
    }
 
    //析构函数
    public function __destruct() {
        $this->free_result();
        $use_time = ($this-> microtime_float())-($this->time);
        $this->write_log("完成整个查询任务,所用时间为".$use_time);
        if($this->is_log){
            fclose($this->handle);
        }
    }
     
    //写入日志文件
    public function write_log($msg=''){
        if($this->is_log){
            $text = date("Y-m-d H:i:s")." ".$msg."
";
            fwrite($this->handle,$text);
        }
    }
     
    //获取毫秒数
    public function microtime_float() {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}
 
原文地址:https://www.cnblogs.com/zoubizhici/p/5585724.html