PHP基于pdo的数据库操作类【可支持mysql、sqlserver及oracle】


Posted in PHP onMay 21, 2018

本文实例讲述了PHP基于pdo的数据库操作类。分享给大家供大家参考,具体如下:

工作中需要操作sqlserver、oracle都是使用的这个类,当时是在别人的基础上改进了,现在分享下

<?php
class Pdodb{
  protected $pdo;
  protected $res;
  protected $config;
  /*构造函数*/
  function __construct($config){
    $this->Config = $config;
    $this->connect();
  }
  /*数据库连接*/
  public function connect(){
    try {
       $this->pdo= new PDO($this->Config['dsn'], $this->Config['username'], $this->Config['password']);//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
       $this->pdo->query("set names utf8");
    }catch(Exception $e){
      echo '数据库连接失败,详情: ' . $e->getMessage () . ' 请在配置文件中数据库连接信息';
      exit ();
    }
    /*
    if($this->Config['type']=='oracle'){
      $this->pdo->query("set names {$this->Config['charset']};");
    }else{
      $this->pdo->query("set names {$this->Config['charset']};");
    }
    */
    //把结果序列化成stdClass
    //$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
    //自己写代码捕获Exception
    //$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);//属性名 属性值 数组以关联数组返回
  }
  /*数据库关闭*/
  public function close(){
    $this->pdo = null;
  }
  //用于有记录结果返回的操作,特别是SELECT操作
  public function query($sql,$return=false){
    $res = $this->pdo->query($sql);
    if($res){
      $this->res = $res; // 未返回 return $this->res;
    }
    if($return){
      return $res;
    }
  }
  //主要是针对没有结果集合返回的操作,比如INSERT、UPDATE、DELETE等操作
  public function exec($sql,$return=false){
    $res = $this->pdo->exec($sql);
    if($res){
      $this->res = $res;
    }
    if($return){//返回操作是否成功 成功返回1 失败0
      return $res;
    }
  }
  //将$this->res以数组返回(全部返回)
  public function fetchAll(){
    return $this->res->fetchAll();
  }
  //将$this->res以数组返回(一条记录)
  public function fetch(){
    return $this->res->fetch();
  }
  //返回所有字段
  public function fetchColumn(){
    return $this->res->fetchColumn();
  }
  //返回最后插入的id
  public function lastInsertId(){
    return $this->res->lastInsertId();
  }
  //返回最后插入的id
  public function lastInsertId2(){
    return $this->pdo->lastInsertId();
  }
  /**
  * 参数说明
  * string/array $table 数据库表,两种传值模式
  * 普通模式:
  * 'tb_member, tb_money'
  * 数组模式:
  * array('tb_member', 'tb_money')
  * string/array $fields 需要查询的数据库字段,允许为空,默认为查找全部,两种传值模式
  * 普通模式:
  * 'username, password'
  * 数组模式:
  * array('username', 'password')
  * string/array $sqlwhere 查询条件,允许为空,两种传值模式
  * 普通模式(必须加上and,$sqlwhere为空 1=1 正常查询):
  * 'and type = 1 and username like "%os%"'
  * 数组模式:
  * array('type = 1', 'username like "%os%"')
  * string $orderby 排序,默认为id倒序
  *int $debug 是否开启调试,开启则输出sql语句
  * 0 不开启
  * 1 开启
  * 2 开启并终止程序
  * int $mode 返回类型
  * 0 返回多条记录
  * 1 返回单条记录
  * 2 返回行数
  */
  public function select($table, $fields="*", $sqlwhere="", $orderby="", $debug=0, $mode=0){
    //参数处理
    if(is_array($table)){
      $table = implode(', ', $table);
    }
    if(is_array($fields)){
      $fields = implode(',',$fields);
      /*
      if($this->Config['type']=='oracle'){
        //$fields = implode(',',$fields);//CUSTOMER_ID,FIRST_NAME,LAST_NAME,EMAIL
        //$fields = implode(",'UTF8','ZHS16GBK') ,convert(",$fields);
        //$fields="convert(".$fields.",'UTF8','ZHS16GBK')";
      }else{
        $fields = implode(',',$fields);
      }
      */
    }
    if(is_array($sqlwhere)){
      $sqlwhere = ' and '.implode(' and ', $sqlwhere);
    }
    //数据库操作
    if($debug === 0){
      if($mode === 2){ //统计
        $this->query("select count(*) from $table where 1=1 $sqlwhere");
        $return = $this->fetchColumn();
      }else if($mode === 1){ //返回一条
        $this->query("select $fields from $table where 1=1 $sqlwhere $orderby");
        $return = $this->fetch();
      }else{
        $this->query("select $fields from $table where 1=1 $sqlwhere $orderby");
        $return = $this->fetchAll();//如果 $this->res为空即sql语句错误 会提示Call to a member function fetchAll() on a non-object
      }
      return $return;
    }else{
        if($mode === 2){
          echo "select count(*) from $table where 1=1 $sqlwhere";
        }else if($mode === 1){
          echo "select $fields from $table where 1=1 $sqlwhere $orderby";
        }else{
          echo "select $fields from $table where 1=1 $sqlwhere $orderby";
        }
        if($debug === 2){
          exit;
        }
    }
  }
  /**
  * 参数说明
  * string/array $table 数据库表,两种传值模式
  * 普通模式:
  * 'tb_member, tb_money'
  * 数组模式:
  * array('tb_member', 'tb_money')
  * string/array $set 需要插入的字段及内容,两种传值模式
  * 普通模式:
  * 'username = "test", type = 1, dt = now()'
  * 数组模式:
  * array('username = "test"', 'type = 1', 'dt = now()')
  * int $debug 是否开启调试,开启则输出sql语句
  * 0 不开启
  * 1 开启
  * 2 开启并终止程序
  * int $mode 返回类型
  * 0 无返回信息
  * 1 返回执行条目数
  * 2 返回最后一次插入记录的id
  */
  public function oic_insert($table, $set, $debug=0, $mode=0){
    //参数处理
    if(is_array($table)){
      $table = implode(', ', $table);
    }
    if(is_array($set)){
      $s='';$i=0;
      foreach($set as $k=>$v){
        $i++;
        $s[$i]=$k;//,连接
        $val[$i]=$v;
      }
      $sarr=implode(",",$s);//去掉最后一个,
      //array_pop($sarr);
      $set=implode("','",$val);////15221579236','张三','','2001','8','4','女','是
      //$set = implode(', ', $set);
    }
    //数据库操作
    if($debug === 0){
      if($mode === 2){
        $this->query("insert into $table ($sarr) values('".$set."')");
        //$return = $this->lastInsertId();
      }else if($mode === 1){
        $this->exec("insert into $table ($sarr) values('".$set."')");
        $return = $this->res;
      }else{
        $this->query("insert into $table ($sarr) values('".$set."')");
        $return = NULL;
      }
      return $return;
    }else{
      echo "insert into $table ($sarr) values('".$set."')";
      if($debug === 2){
        exit;
      }
    }
  }
  public function insert($table, $set, $debug=0, $mode=0){
    //参数处理
    if(is_array($table)){
      $table = implode(', ', $table);
    }
    if(is_array($set)){
      $s='';
      foreach($set as $k=>$v){
        $s.=$k."='".$v."',";//,连接
      }
      $sarr=explode(',',$s);//去掉最后一个,
      array_pop($sarr);
      $set=implode(',',$sarr);
      //$set = implode(', ', $set);
    }
    //数据库操作
    if($debug === 0){
      if($mode === 2){
        $this->query("insert into $table set $set");
        $return = $this->pdo->lastInsertId();
      }else if($mode === 1){
        $this->exec("insert into $table set $set");
        $return = $this->res;
      }else{
        $this->query("insert into $table set $set");
        $return = NULL;
      }
      return $return;
    }else{
      echo "insert into $table set $set";
      if($debug === 2){
        exit;
      }
    }
  }
  /**
  * 参数说明
  * string $table 数据库表,两种传值模式
  * 普通模式:
  * 'tb_member, tb_money'
  * 数组模式:
  * array('tb_member', 'tb_money')
  * string/array $set 需要更新的字段及内容,两种传值模式
  * 普通模式:
  * 'username = "test", type = 1, dt = now()'
  * 数组模式:
  * array('username = "test"', 'type = 1', 'dt = now()')
  * string/array $sqlwhere 修改条件,允许为空,两种传值模式
  * 普通模式:
  * 'and type = 1 and username like "%os%"'
  * 数组模式:
  * array('type = 1', 'username like "%os%"')
  * int $debug 是否开启调试,开启则输出sql语句
  * 0 不开启
  * 1 开启
  * 2 开启并终止程序
  * int $mode 返回类型
  * 0 无返回信息
  * 1 返回执行条目数
  */
  public function update($table, $set, $sqlwhere="", $debug=0, $mode=0){
    //参数处理
    if(is_array($table)){
      $table = implode(', ', $table);
    }
    if(is_array($set)){
      $s='';
      foreach($set as $k=>$v){
        $s.=$k."='".$v."',";
      }
      $sarr=explode(',',$s);//去掉最后一个,
      array_pop($sarr);
      $set=implode(',',$sarr);
      //$set = implode(', ', $set);
    }
    if(is_array($sqlwhere)){
      $sqlwhere = ' and '.implode(' and ', $sqlwhere);
    }
    //数据库操作
    if($debug === 0){
      if($mode === 1){
        $this->exec("update $table set $set where 1=1 $sqlwhere");
        $return = $this->res;
      }else{
        $this->query("update $table set $set where 1=1 $sqlwhere");
        $return = true;
      }
      return $return;
    }else{
      echo "update $table set $set where 1=1 $sqlwhere";
      if($debug === 2){
        exit;
      }
    }
  }
  /**
  * 参数说明
  * string $table 数据库表
  * string/array $sqlwhere 删除条件,允许为空,两种传值模式
  * 普通模式:
  * 'and type = 1 and username like "%os%"'
  * 数组模式:
  * array('type = 1', 'username like "%os%"')
  * int $debug 是否开启调试,开启则输出sql语句
  * 0 不开启
  * 1 开启
  * 2 开启并终止程序
  * int $mode 返回类型
  * 0 无返回信息
  * 1 返回执行条目数
  */
  public function delete($table, $sqlwhere="", $debug=0, $mode=0){
    //参数处理
    if(is_array($sqlwhere)){
      $sqlwhere = ' and '.implode(' and ', $sqlwhere); //是字符串需自己加上and
    }
    //数据库操作
    if($debug === 0){
      if($mode === 1){
        $this->exec("delete from $table where 1=1 $sqlwhere");
        $return = $this->res;
      }else{
        $this->query("delete from $table where 1=1 $sqlwhere");
        $return = NULL;
      }
      return $return;
    }else{
      echo "delete from $table where 1=1 $sqlwhere";
      if($debug === 2){
        exit;
      }
    }
  }
}
/*
sqlserver 配置 extension=php_pdo_mssql.dll和extension=php_pdo_sqlsrv.dll 安装对应的 ntwdblib.dll
http://msdn.microsoft.com/en-us/library/cc296170.aspx 下载php版本对应的sqlsrv扩展
sqlserver 配置 odbc连接需开启extension=php_pdo_odbc.dll
*/
$mssql2008_config=array(
  'dsn'=>'odbc:Driver={SQL Server};Server=192.168.1.60;Database=his',//数据库服务器地址
  'username'=>'sa',
  'password'=>'xxxxx',
);
$mssql=new Pdodb($mssql2008_config);
$sql="select * from
(
  select row_number()over(order by tempcolumn)temprownumber,*
    from (
      select top 10 tempcolumn=0,a.*
      from DA_GR_HBFS a
      where 1=1
    ) t
) tt
where temprownumber>0";
$mssql->query($sql);
while($res=$mssql->fetch()){
  $data[]=$res;
}
print_r($data);exit;
//mysql 操作
$msyql_config=array(
  'dsn'=>'mysql:host=localhost;dbname=talk',
  'username'=>'root',
  'password'=>'123456'
);
$mysql=new PDO_DB($msyql_config);
$sql = 'SELECT user_id, user_name, nickname FROM et_users ';
$mysql->query($sql);
$data=$mysql->fetchAll();
print_r($data);exit;
//oracle 操作
$oci_config=array(
  'dsn'=>'oci:dbname=orcl',
  'username'=>'BAOCRM',
  'password'=>'BAOCRM'
);
$oracle=new PDO_DB($oci_config);
//print_r($oracle);exit;//PDO_DB Object ( [pdo:protected] => PDO Object ( ) [res:protected] => [config:protected] => [Config] => Array ( [dsn] => oci:dbname=orcl [name] => PWACRM [password] => PWACRM ) )
$sql="select * from CUSTOMER_LEVEL t";
$oracle->query($sql);
$data=$oracle->fetchAll();
print_r($data);exit;
/*
Array
(
  [0] => Array
    (
      [LEVEL_ID] => 1
      [0] => 1
      [LEVEL_NAME] => 普通会员
      [1] => 普通会员
      [LEVEL_DETAIL] => 普通会员
      [2] => 普通会员
      [SORT_NUMBER] => 15
      [3] => 15
      [CREATE_TIME] => 12-7月 -12
      [4] => 12-7月 -12
      [CREATE_BY] => 1
      [5] => 1
      [UPDATE_TIME] => 12-7月 -12
      [6] => 12-7月 -12
      [UPDATE_BY] => 1
      [7] => 1
      [STATE] => 正常
      [8] => 正常
    )
)*/
?>

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP中include()与require()的区别说明
Mar 10 PHP
PHP面向对象的进阶学习(抽像类、接口、final、类常量)
May 07 PHP
解析PHPExcel使用的常用说明以及把PHPExcel整合进CI框架的介绍
Jun 24 PHP
php 读取文件头判断文件类型的实现代码
Aug 05 PHP
php加密算法之实现可逆加密算法和解密分享
Jan 21 PHP
thinkphp数据查询和遍历数组实例
Nov 28 PHP
php删除左端与右端空格的方法
Nov 29 PHP
CodeIgniter表单验证方法实例详解
Mar 03 PHP
CI框架出现mysql数据库连接资源无法释放的解决方法
May 17 PHP
浅谈PHP检查数组中是否存在某个值 in_array 函数
Jun 13 PHP
Yii2中YiiBase自动加载类、引用文件方法分析(autoload)
Jul 25 PHP
PHP面向对象程序设计(OOP)之方法重写(override)操作示例
Dec 21 PHP
PHP+MariaDB数据库操作基本技巧备忘总结
May 21 #PHP
PhpStorm本地断点调试的方法步骤
May 21 #PHP
PHP自动识别当前使用移动终端
May 21 #PHP
PHP连接MySQL数据库并以json格式输出
May 21 #PHP
PHP 访问数据库配置通用方法(json)
May 20 #PHP
PHP生成腾讯云COS接口需要的请求签名
May 20 #PHP
windows环境下使用Composer安装ThinkPHP5
May 18 #PHP
You might like
PHP5中使用PDO连接数据库的方法
2010/08/01 PHP
php数字转汉字代码(算法)
2011/10/08 PHP
php格式化电话号码的方法
2015/04/24 PHP
Zend Framework前端控制器用法示例
2016/12/11 PHP
js 方法实现返回多个数据的代码
2009/04/30 Javascript
Javascript面向对象扩展库代码分享
2012/03/27 Javascript
基于jQuery中对数组进行操作的方法
2013/04/16 Javascript
jQuery弹性滑动导航菜单实现思路及代码
2013/05/02 Javascript
javascript实现文本域写入字符时限定字数
2014/02/12 Javascript
javascript中的this详解
2014/12/08 Javascript
javascript DIV实现跟随鼠标移动
2020/03/19 Javascript
对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache详解
2016/04/11 Javascript
完美解决node.js中使用https请求报CERT_UNTRUSTED的问题
2017/01/08 Javascript
Bootstrap入门教程一Hello Bootstrap初识
2017/03/02 Javascript
浅谈在不使用ssr的情况下解决Vue单页面SEO问题(2)
2018/11/08 Javascript
BootStrap table实现表格行拖拽效果
2018/12/01 Javascript
Vue自定义全局Toast和Loading的实例详解
2019/04/18 Javascript
python实现爬虫下载漫画示例
2014/02/16 Python
pycharm安装图文教程
2017/05/02 Python
用python做一个搜索引擎(Pylucene)的实例代码
2017/07/05 Python
Django 根据数据模型models创建数据表的实例
2018/05/27 Python
带你认识Django
2019/01/15 Python
教你一步步利用python实现贪吃蛇游戏
2019/06/27 Python
python cv2读取rtsp实时码流按时生成连续视频文件方式
2019/12/25 Python
Python tkinter模版代码实例
2020/02/05 Python
python 实现两个线程交替执行
2020/05/02 Python
Python数据相关系数矩阵和热力图轻松实现教程
2020/06/16 Python
Python importlib模块重载使用方法详解
2020/10/13 Python
英国知名的皮手套品牌:Dents
2016/11/13 全球购物
马来西亚最大的在线隐形眼镜商店:MrLens
2019/03/27 全球购物
英国DVD和蓝光碟片购买网站:Zoom.co.uk(电影和电视)
2019/09/23 全球购物
澳洲最大的时尚奢侈品电商平台:Cettire
2020/06/15 全球购物
施工班组长岗位职责
2014/01/05 职场文书
杜甫草堂导游词
2015/02/03 职场文书
MySQL infobright的安装步骤
2021/04/07 MySQL
SQL Server使用导出向导功能
2022/04/08 SQL Server