<?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;
} }

  

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

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

    可同时操作多个不同类型的数据库. 完全不用考虑数据类型的差别,再也不用想字符型字段加不加单引号. 调用非常简单,对数据库的主要操作一般只需要一行代码. 支持mssql事务回滚. 可自动生成和输出sql ...

  2. ecshop操作数据库类

    ECShop v2.7.2没有使用一些开源的数据库操作类,比如adodb或者PEAR,而是封装了自己的实现.这样做的好处是实现非常轻量,只有一个文件,27Kb,大大减小了分发包的文件大小.另外,当网站 ...

  3. Python操作数据库类 Oracle、Sqlserver、PostgreSQL

    我在工作中经常使用Python,特点很明显,轻量,效率还不错,尤其在维护或者自动化方面. 下面是我使用到的访问数据库(Oracle.Sqlserver.PostgreSQL)的公共类. 一.Oracl ...

  4. C++ 操作数据库类

    #pragma once #include <string> #include <windows.h> #include <algorithm> #include ...

  5. mybatis 操作数据库(05)

    类型转换.动态排序,查询接口与mapper对应关系说明及其注意事项 一.MyBatis 自带写常见类型转换器.例如:java 类中 String 对应 mySQL中的varchar 二.自定义类型转换 ...

  6. 用于JDBC操作数据库的公共类

    /* * @(#)CommonSql.java 2011-9-5 * * Copyright 2011 Bianjing,All rights reserved. */ import java.sql ...

  7. JDBC操作数据库 封装好的工具类

    mysql sqlserver oracle 数据库的驱动jar包http://download.csdn.net/download/csdn576038874/8833683package cn.h ...

  8. SQLserver数据库操作帮助类SqlHelper

    1 SqlHelper源码 using System; using System.Data; using System.Xml; using System.Data.SqlClient; using ...

  9. .NET使用DAO.NET实体类模型操作数据库

    一.新建项目 打开vs2017,新建一个项目,命名为orm1 二.新建数据库 打开 SqlServer数据库,新建数据库 orm1,并新建表 student . 三.新建 ADO.NET 实体数据模型 ...

随机推荐

  1. MongoDB的主要特性概述

    一.文档数据模型 文档是一组属性名和属性的集合.相较于关系数据库复杂的规范化,面向文档的数据模型很容易以聚合的形式来表示数据.文档采用无Schema的形式,这种做法带来了一定的优势:首先,由应用程序, ...

  2. PHP实现下载功能之流程分析

    客户端从服务端下载文件的流程分析: 浏览器发送一个请求,请求访问服务器中的某个网页(如:down.php),该网页的代码如下. 服务器接受到该请求以后,马上运行该down.php文件 运行该文件的时候 ...

  3. 获取android SDCard存储大小

    //File path = Environment.getDataDirectory();//手机内置空间 1.获取SD卡的路径 File path = Environment.getExternal ...

  4. C# 平时碰见的问题【4】

    1. 模糊查询 like的参数化写法 string keyword="value"; // 要模糊匹配的值 错误示范:   sql:    string strSql=" ...

  5. mono的https使用使用事项

    private static void SetCertificatePolicy() { if( ServicePointManager.ServerCertificateValidationCall ...

  6. python 序列化之JSON和pickle详解

    JSON模块 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类 ...

  7. 安装使用rspec

    一,安装ruby. 二,运行命令,安装rspec的gem包: gem install rspec 会看到如下的结果: Fetching: rspec-core-2.14.7.gem (100%) Fe ...

  8. Oracle Rac crs无法启动

    OS:ORACLE LINUX 5.7 DB:11.2.0.3 RAC:YES 故障:1.两节点RAC,节点分别为linuxdb1.linuxdb2,其中节点linuxdb2服务器出现故障,无法启动2 ...

  9. CSV 文件读取类

    class CsvReader { private $csv_file; private $spl_object = null; private $error; public function __c ...

  10. [Environment Build] Win10下Appach配置

    1. Apache下载,登录http://httpd.apache.org/download.cgi,选择Files for Microsoft Windows, 有以下几个选择, 我选择的是Apac ...