PHP操作数据库类

<?php/** * 功能:  数据库操作类 . * 作者:  赵铭哲  * 日期: 2016-05-23 * 时间: 9:43 */

namespace ZH\DataBase;

use \Exception as Exception;

class mysql {

    #region ----声明公用变量----    public $db;             //数据库连接对象    public $config;         //数据库配置数据    public $server;         //服务器连接地址    public $username;       //数据库用户名    public $password;       //数据库密码    public $sql;            //sql语句变量    public $defaultDatabase;//默认设置的数据库    public $limitcount;     //限制的数量    public $message = array(        ‘charset‘=>‘‘,      //返回        ‘execsql‘=>‘‘,      //执行的sql语句        ‘resmsg‘=>‘‘,       //结果信息        ‘recordmsg‘=>‘‘,    //记录信息        ‘affected_rows‘=>0, //上次执行SQL所影响的行数        ‘errormsg‘=>‘‘,     //错误信息        ‘errorcode‘=>‘‘,    //错误代码        ‘errorline‘=>‘‘,    //错误行        ‘errorfile‘=>‘‘     //错误文件    );    #endregion

    #region ----声明公用常量----    const SELECT = "SELECT ";    const INSERT = "INSERT ";    const UPDATE = "UPDATE ";    const DELETE = "DELETE ";    const FROM = "FROM ";    const WHERE = " WHERE 1=1 ";    const INTO = "INTO ";    const SET = "SET ";    const VALUES = "VALUES ";    const ORDERBY = " ORDER BY ";    const GROUPBY = " GROUP BY ";    const HAVING = "HAVING ";    const LIMIT = " LIMIT ";    const JOIN = "JOIN ";    const ON = "ON ";    const _AND = "AND ";    const _OR = "OR ";    const _LIKE = "LIKE ";    const _IN = "IN ";    const _BETWEEN = "BETWEEN ";    #endregion

    /**     * 构造函数     */    public function __construct() {        //开发环境        $this->server = "localhost";        $this->port = "3306";        $this->username = "root";        $this->password = "123456";    }

    /**     * 功能:析构函数     * 作者: 赵铭哲     * 日期: 2016-06-03     */    public function _destruct(){        $this->server = ‘‘;        $this->username = ‘‘;        $this->password = ‘‘;        $this->port = ‘‘;        $this->defaultDatabase = ‘‘;        $this->dbDisconnect();    }

    #region ----数据库连接----    /**     * 功能:连接数据库     * 作者: 赵铭哲     * 日期: 2016-05-28     * @return string     */    public function dbConnect(){        try{            //连接mysql数据库            $this->db=mysql_connect($this->server.‘:‘.$this->port,$this->username,$this->password);            $charset = mysql_client_encoding($this->db);            if($this->db == false){                $this->message[‘errormsg‘] = "Connected failed " . mysqli_connect_error();;            }else{                $this->message[‘resmsg‘] = "Connected successfully.";            }            $this->message[‘charset‘] = $charset;        }catch (Exception $ex){            $this->message[‘errorcode‘] = "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] = "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] = "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] = "Exception file:".$ex->getFile();        }        return $this->message;    }

    /**     * 功能:断开数据库连接     * 作者: 赵铭哲     * 日期: 2016-05-28     */    public function dbDisconnect(){        mysql_close($this->db);    }

    /**     * 功能:选择数据库     * 作者: 赵铭哲     * 日期: 2016-06-12     */    public function dbSelectDataBase($databaseName){        try{            if(isset($databaseName)){                mysql_select_db($databaseName);            }else{                mysql_select_db($this->defaultDatabase);            }            $this->message[‘resmsg‘] = "Select Database successfully.";        }catch (Exception $ex){            $this->message[‘errorcode‘] = "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] = "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] = "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] = "Exception file:".$ex->getFile();        }        return $this->message;    }

    #endregion

    #region ----数据库查询----    /**     * 功能:通用执行     * 作者: 赵铭哲     * 日期: 2016-06-12     * @param $sql      普通的SQL语句     * @return array    返回一个信息数组,方便查看执行后的结果     */    public function dbExec($sql){        $this->dbConnect();        $this->dbSelectDataBase($this->defaultDatabase);        try{            $isQuery = mysql_query($sql);            if($isQuery){                $this->message[‘resmsg‘] .= "Query Successful";            }else{                $this->message[‘resmsg‘] .= "Query Failed";            }            $this->message[‘affected_rows‘] = mysql_affected_rows();        }catch (Exception $ex){            $this->message[‘errorcode‘] .= "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] .= "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] .= "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] .= "Exception file:".$ex->getFile();        }        $this->dbDisconnect();        return $this->message;    }

    /**     * 功能:通用查询获取单条数据     * 作者: 赵铭哲     * 日期: 2016-06-03     * @param $sql      普通的SQL语句     * @return resource 返回数组格式的单条数据信息     */    public function dbQuerySingle($sql){        $this->dbConnect();        $this->dbSelectDataBase($this->defaultDatabase);        try{            $obj = mysql_query($sql);            $row = mysql_fetch_array($obj, MYSQL_BOTH);            $this->message[‘affected_rows‘] = mysql_affected_rows();            mysql_free_result($obj);            return $row;        }catch (Exception $ex){            $this->message[‘errorcode‘] .= "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] .= "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] .= "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] .= "Exception file:".$ex->getFile();        }        $this->dbDisconnect();    }

    /**     * 功能:获取多条数据     * 作者: 赵铭哲     * 日期: 2016-06-14     * @param $sql      普通的SQL语句     * @return array    返回多条数据的数组     */    public function dbQueryMutiple($sql){        $this->dbConnect();        $this->dbSelectDataBase($this->defaultDatabase);        try{            $result = array();            $obj = mysql_query($sql);            while($row = mysql_fetch_array($obj, MYSQL_BOTH)){                array_push($result,$row);            }            $this->message[‘affected_rows‘] = mysql_affected_rows();            mysql_free_result($obj);            return $result;        }catch (Exception $ex){            $this->message[‘errorcode‘] .= "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] .= "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] .= "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] .= "Exception file:".$ex->getFile();        }        $this->dbDisconnect();    }

    /**     * 功能:扩展查询功能     * 作者: 赵铭哲     * 日期: 2016-06-14     * @param $table    表名     * @param $cols     列名:数组格式(array(1,2,3))|字符串格式(1,2,3)     * @param $where    Where语句:一维数组格式(array(a=>‘1‘,b=>‘2‘))|字符串格式(a=‘1‘,b=‘2‘)     * @param $order    OrderBy语句:字符串格式(id asc|id desc)     * @param $group    GroupBy语句:字符串格式(id)     * @param $limit    Limit语句:字符串格式(1|1,2)     * @return array     */    public function dbQueryExt($table,$cols=‘*‘,$where=null,$order=null,$group=null,$limit=null){        $this->dbConnect();        $this->dbSelectDataBase($this->defaultDatabase);        try{            $result = array();            $strWhere = self::WHERE;            $strCols = ‘‘;

            if(is_array($cols)){                foreach($cols as $kc => $vc){                    $strCols .= $vc.‘,‘;                }                $strCols = substr($strCols,0,strlen($strCols)-1);            }else if(is_string($cols)){                $strCols = $cols;            }            $this->sql = self::SELECT.$strCols.‘ ‘.self::FROM.$table;            if(is_array($where)){                foreach($where as $kw=>$vw){                    $strWhere .= " and ".$kw."=‘".$vw."‘";                }                $strWhere = substr($strWhere,0,strlen($strWhere)-5);            }else{                $strWhere .= $where;            }            $this->sql .= $strWhere;            if(isset($order)){                $this->sql .= self::ORDERBY.$order;            }            if(isset($group)){                $this->sql .= self::GROUPBY.$group;            }            if(isset($limit)){                $this->sql .= self::LIMIT.$limit;            }            $this->message[‘execsql‘] = $this->sql;            $obj = mysql_query($this->sql);            while($row = mysql_fetch_array($obj, MYSQL_BOTH)){                array_push($result,$row);            }            $this->message[‘affected_rows‘] = mysql_affected_rows();            mysql_free_result($obj);            return $result;        }catch (Exception $ex){            $this->message[‘errorcode‘] .= "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] .= "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] .= "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] .= "Exception file:".$ex->getFile();        }        $this->dbDisconnect();    }

    /**     * 功能:扩展查询功能2     * 作者: 赵铭哲     * 日期: 2016-07-20     * @param $table         表名     * @param string $cols   列名:数组格式(array(1,2,3))|字符串格式(1,2,3)     * @param null $where    Where语句:     *                          一维数组格式(array(a=>‘1‘,b=>‘2‘))|字符串格式(a=‘1‘,b=‘2‘)     *                          二维数组格式(array(array(a1=>‘1‘,a2=>‘2‘),array(a3=>‘3‘,a4=>‘4‘))|array(array(1,2),array(3,4)))     * @return array     */    public function dbQueryExtTwo($table,$cols=‘*‘,$where=null,$pager = array(),$sort = array()){        try{            $result = array();            $strWhere = self::WHERE;            $strCols = ‘‘;

            if(is_array($cols)){                foreach($cols as $kc => $vc){                    $strCols .= $vc.‘,‘;                }                $strCols = substr($strCols,0,strlen($strCols)-1);            }else if(is_string($cols)){                $strCols = $cols;            }            $this->sql = self::SELECT.$strCols.‘ ‘.self::FROM.$table;            if(is_array($where)){                $startIndex = 0;                foreach($where as $kw=>$vw){                    if(is_array($vw)){                        foreach($vw as $k => $v){                            if($startIndex == 0){                                $strWhere .= " and ".$k.$this->formatWhere($v);                            }else{                                $strWhere .= $k.$this->formatWhere($v)." and ";                            }                        }                        if($startIndex > 0){                            $strWhere = substr($strWhere,0,strlen($strWhere)-5);                        }                        $strWhere .= " or  ";                    }else{                        $strWhere .= " and ".$kw."=‘".$vw."‘";                    }                    $startIndex = $startIndex + 1;                }                $strWhere = substr($strWhere,0,strlen($strWhere)-5);            }else{                $strWhere .= $where;            }            //增加分页的功能            if (!empty($pager)) {                if (!isset($pager[‘page‘]) || $pager[‘page‘] < 1) {                    $pager[‘page‘] = 1;                }                $offset = ($pager[‘page‘] - 1) * $pager[‘page_size‘];                $limit = $pager[‘page_size‘];                $strWhere .= sprintf(‘ LIMIT %d,%d‘, $offset, $limit);            }            $this->sql .= $strWhere;            $this->message[‘execsql‘] = $this->sql;            $result = $this->dbQueryMutiple($this->sql);            return $result;        }catch (Exception $ex){            $this->message[‘errorcode‘] .= "Exception code:".$ex->getCode();            $this->message[‘errormsg‘] .= "Exception msg:".$ex->getMessage();            $this->message[‘errorline‘] .= "Exception line:".$ex->getLine();            $this->message[‘errorfile‘] .= "Exception file:".$ex->getFile();        }        $this->dbDisconnect();    }    #endregion

    #region ----数据库插入----    /**     * 功能:通用插入单条数据     * 作者: 赵铭哲     * 日期: 2016-06-14     * @param $table    表名     * @param $cols     列名:数组格式(array(1,2,3))|字符串格式(1,2,3)     * @param $values   值:数组格式(array(1,2,3))|字符串格式(1,2,3)     */    public function dbInsertSingle($table,$cols,$values){        //判断$cols,$values是否是数组,是则自动组合,否则直接返回值        $strCols = ‘‘;        $strValues = ‘‘;        if(is_array($cols)){            foreach($cols as $kc => $vc){                $strCols .= $vc.‘,‘;            }            $strCols = substr($strCols,0,strlen($strCols)-1);        }else if(is_string($cols)){            $strCols = $cols;        }else{            $this->message[‘errmsg‘] = "数据类型不合法";        }

        if(is_array($values)){            foreach($values as $kv => $vv){                $strValues .= "‘".$vv."‘,";            }            $strValues = substr($strValues,0,strlen($strValues)-1);        }else if(is_string($values)){            $strValues = $this->CombinationInsert($values);        }else{            $this->message[‘errmsg‘] = "数据类型不合法";        }        $this->sql = self::INSERT.self::INTO.$table."(".$strCols.") ".self::VALUES."(".$strValues.")";        $this->dbExec($this->sql);    }    #endregion

    #region ----数据库修改----    /**     * 功能:通用更新     * 作者: 赵铭哲     * 日期: 2016-06-14     * @param $table    表名     * @param $values   更新的数据:数组格式(array(a=>‘1‘,b=>‘2‘))|字符串格式(a=‘1‘,b=‘2‘)     * @Param $where    参数Where:数组格式(array(a=>‘1‘,b=>‘2‘))|字符串格式(a=‘1‘,b=‘2‘)     */    public function dbUpdate($table,$values,$where=null){        $strValues = ‘‘;        $strWhere = ‘‘;        if(is_array($values)){            foreach($values as $k=>$v){                $strValues .= $k."=‘".$v."‘,";            }            $strValues = substr($strValues,0,strlen($strValues)-1);        }else{            $strValues = $strValues;        }        $this->sql = self::UPDATE.$table.‘ ‘.self::SET.$strValues;

        if(is_array($where)){            foreach($where as $kw=>$vw){                $strWhere .= $kw."=‘".$vw."‘ and ";            }            $strWhere = substr($strWhere,0,strlen($strWhere)-5);        }else{            $strWhere = $where;        }        $this->sql .= self::WHERE.self::_AND.$strWhere;        $this->dbExec($this->sql);    }    #endregion

    #region ----数据库删除----    /**     * 功能:通用删除     * 作者: 赵铭哲     * 日期: 2016-06-14     * @param $table    表名     * @param $where    Where语句:数组格式(array(a=>‘1‘,b=>‘2‘))|字符串格式(a=‘1‘,b=‘2‘)     */    public function dbDelete($table,$where){        $strWhere = ‘‘;        $this->sql = self::DELETE.self::FROM.$table.self::WHERE;        if(is_array($where)){            foreach($where as $kw=>$vw){                $strWhere .= $kw."=‘".$vw."‘ and ";            }            $strWhere = substr($strWhere,0,strlen($strWhere)-5);        }else{            $strWhere = $where;        }        $this->sql .= self::_AND.$strWhere;        $this->dbExec($this->sql);        print_r($this->sql);    }    #endregion

    #region ----格式化返回数据----    /**     * 功能:格式化数据     * 作者: 赵铭哲     * 日期: 2016-07-21     * @param $data     查询出来的结果集:数组形式     * @return array     */    public function formatData($data){        return array(            ‘statistic‘ => count($data),            ‘data‘ => $data,        );    }

    /**     * 功能:格式化Where子句     * 作者: 赵铭哲     * 日期: 2016-07-21     * @param $condition    数组格式(array(‘operation‘=>‘eq‘,‘value‘=>‘‘))|字符串格式(=‘‘)     * @return string     */    public function formatWhere($condition){        if(is_array($condition)){            if($condition[‘operation‘] == "lt"){                return "<‘".$condition[‘value‘]."‘";            }else if($condition[‘operation‘] == "eq"){                return "=‘".$condition[‘value‘]."‘";            }else if($condition[‘operation‘] == "gt"){                return ">‘".$condition[‘value‘]."‘";            }else if($condition[‘operation‘] == "le"){                return "<=‘".$condition[‘value‘]."‘";            }else if($condition[‘operation‘] == "ge"){                return ">=‘".$condition[‘value‘]."‘";            }else if($condition[‘operation‘] == "neq"){                return "<>‘".$condition[‘value‘]."‘";            }else if($condition[‘operation‘] == "like"){                return "like‘%".$condition[‘value‘]."%‘";            }else if($condition[‘operation‘] == "in"){                if(is_array($condition[‘value‘])){                    return " in(".implode(‘,‘,$condition[‘value‘]).")";                }else{                    return " in(‘".$condition[‘value‘]."‘)";                }            }        }else {            return "=‘".$condition."‘";        }    }    #endregion

    /**     * 功能:转换编码格式     * 作者: 赵铭哲     * 日期: 2016-06-06     */    function ConvertEncode($value,$old_Encode,$new_Encode){        header("content-Type: text/html; charset=Utf-8");        $result = mb_convert_encoding($value, $old_Encode, $new_Encode);        return $result;    }

    /**     * 功能:组合传入的字符为数据库插入时候的值     * 作者: 赵铭哲     * 日期: 2016-06-14     * @param $value     * @return string     */    function CombinationInsert($value){        $result = ‘‘;        if(strstr($value,‘,‘) > -1){            $valTemp = explode(‘,‘,$value);            foreach($valTemp as $k => $v){                $result .= "‘".$v."‘,";            }            $result = substr($result,0,strlen($result)-1);        }else{            $this->message[‘resmsg‘] = "在传入的参数中未找到相关字符";        }        return $result;    }

}
时间: 2024-10-11 11:00:30

PHP操作数据库类的相关文章

非常不错的ASP操作数据库类,支持多数据库MSSQL,ACCESS,ORACLE,MYSQL等

可同时操作多个不同类型的数据库. 完全不用考虑数据类型的差别,再也不用想字符型字段加不加单引号. 调用非常简单,对数据库的主要操作一般只需要一行代码. 支持mssql事务回滚. 可自动生成和输出sql语句方便调试. 使用方法: 1. 修改clsDbctrl.asp文件中的第1行为你自己的数据库位置(修改方法参考下面的CreatConn函数说明).如需连接多个数据库可自行添加,格式相同. 2. 在你新建的asp文件中包含此asp文件.如: <!--#include file="Inc/cls

操作数据库类SQLHelp.cs

using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Utility { public abstract class SqlHelper { protected static string con

java操作数据库的通用的类

package cn.dao; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet;

C#操作数据库SqlHelper类

/* 创建者:菜刀居士的博客 * 创建日期: 2014年09月01号 * 功能:SqlHelper类,操作数据库 * */ namespace Net.String.ConsoleApplication { using System; using System.Data; using System.Data.SqlClient; public sealed class SqlHelper { private SqlHelper() { } public static int ExecuteNon

实例讲解如何使用C++操作MySQL数据库类

用C++操作MySQL数据库类: 注释:这几个类对处理不是很大数据量的操作是很理想的, 但不适宜特大型的数据的查询,因为源码中将查询到的数据直接放入了内存. /* *  project: *           通用模块 ( 用 c++ 处理  mysql 数据库类,像ADO ) *                  *  description: * *           通过DataBase,RecordSet,Record,Field类,实现对mysql数据库的操作 *    包括连接.

数据库操作通用类

DataBase.java 说明: 1. 此类包含对数据库的查询,删除,更新操作.     2. 可以实现对大文本对象的增删改.     3. 利用自建的数据库连接池类, 得到数据库连接.     4. 可以利用Tomcat 自带的连接池, 得到数据库连接 变量:     1. 数据库连接 变量名     : conn 应用范围   : protect 变量类型   : Connection 数据库连接 初始值     : null 是否Static :  否     2. 声明语句 变量名  

ThinkPHP 大D方法思想下的JDBC操作数据库D类

这里我封装出来的D类,是根据ThinkPHP中的D方法中做出来的,其中有些出入的地方,我进行了一些个性化的修正,如:ThinkPHP中操作数据库时,需要在配置文件中定义关于数据库的配置,这里我采用外部接口定义常量的方法进行定义,在D类中实现该接口,实现接口中常量的引用,方便配置的修改:D类中还提供了executeDML和executeDQL这两个方法--传入SQL语句即可进行更复杂的增删查改操作. 该类还存有许多不足的地方. DBConfig.java package cn.zhku.myjdb

SQLserver数据库操作帮助类SqlHelper

1 SqlHelper源码 using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collections; namespace SQL.Access { /// <summary> /// SqlServer数据访问帮助类 /// </summary> public sealed class SqlHelper { #region 私有构造函数和方法

sqlserver数据库操作公共类DBOperate

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using System.Windows.Forms; using  WindowsFormsApplication1.DBTools;//提供数据库连接 namespace liuxw_MPS.DBTools {     ///