Home Backend Development PHP Tutorial PHP database operation class based on pdo [can support mysql, sqlserver and oracle]

PHP database operation class based on pdo [can support mysql, sqlserver and oracle]

Jun 01, 2018 am 11:04 AM
mysql database

This article mainly introduces PHP's pdo-based database operation class, which can realize basic database connections, additions, deletions, modifications, and closing connections. It also supports operations on mysql, sqlserver, oracle and other databases. Friends who need it can Refer to the following

The example of this article describes the PHP database operation class based on pdo. Share it with everyone for your reference, the details are as follows:

This class is used when operating sqlserver and oracle at work. At that time, it was improved on the basis of others. Now I will share it

<?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[&#39;dsn&#39;], $this->Config[&#39;username&#39;], $this->Config[&#39;password&#39;]);//$dbh = new PDO(&#39;mysql:host=localhost;dbname=test&#39;, $user, $pass);
       $this->pdo->query("set names utf8");
    }catch(Exception $e){
      echo &#39;数据库连接失败,详情: &#39; . $e->getMessage () . &#39; 请在配置文件中数据库连接信息&#39;;
      exit ();
    }
    /*
    if($this->Config[&#39;type&#39;]==&#39;oracle&#39;){
      $this->pdo->query("set names {$this->Config[&#39;charset&#39;]};");
    }else{
      $this->pdo->query("set names {$this->Config[&#39;charset&#39;]};");
    }
    */
    //把结果序列化成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 数据库表,两种传值模式
  * 普通模式:
  * &#39;tb_member, tb_money&#39;
  * 数组模式:
  * array(&#39;tb_member&#39;, &#39;tb_money&#39;)
  * string/array $fields 需要查询的数据库字段,允许为空,默认为查找全部,两种传值模式
  * 普通模式:
  * &#39;username, password&#39;
  * 数组模式:
  * array(&#39;username&#39;, &#39;password&#39;)
  * string/array $sqlwhere 查询条件,允许为空,两种传值模式
  * 普通模式(必须加上and,$sqlwhere为空 1=1 正常查询):
  * &#39;and type = 1 and username like "%os%"&#39;
  * 数组模式:
  * array(&#39;type = 1&#39;, &#39;username like "%os%"&#39;)
  * 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(&#39;, &#39;, $table);
    }
    if(is_array($fields)){
      $fields = implode(&#39;,&#39;,$fields);
      /*
      if($this->Config[&#39;type&#39;]==&#39;oracle&#39;){
        //$fields = implode(&#39;,&#39;,$fields);//CUSTOMER_ID,FIRST_NAME,LAST_NAME,EMAIL
        //$fields = implode(",&#39;UTF8&#39;,&#39;ZHS16GBK&#39;) ,convert(",$fields);
        //$fields="convert(".$fields.",&#39;UTF8&#39;,&#39;ZHS16GBK&#39;)";
      }else{
        $fields = implode(&#39;,&#39;,$fields);
      }
      */
    }
    if(is_array($sqlwhere)){
      $sqlwhere = &#39; and &#39;.implode(&#39; and &#39;, $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 数据库表,两种传值模式
  * 普通模式:
  * &#39;tb_member, tb_money&#39;
  * 数组模式:
  * array(&#39;tb_member&#39;, &#39;tb_money&#39;)
  * string/array $set 需要插入的字段及内容,两种传值模式
  * 普通模式:
  * &#39;username = "test", type = 1, dt = now()&#39;
  * 数组模式:
  * array(&#39;username = "test"&#39;, &#39;type = 1&#39;, &#39;dt = now()&#39;)
  * 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(&#39;, &#39;, $table);
    }
    if(is_array($set)){
      $s=&#39;&#39;;$i=0;
      foreach($set as $k=>$v){
        $i++;
        $s[$i]=$k;//,连接
        $val[$i]=$v;
      }
      $sarr=implode(",",$s);//去掉最后一个,
      //array_pop($sarr);
      $set=implode("&#39;,&#39;",$val);////15221579236&#39;,&#39;张三&#39;,&#39;&#39;,&#39;2001&#39;,&#39;8&#39;,&#39;4&#39;,&#39;女&#39;,&#39;是
      //$set = implode(&#39;, &#39;, $set);
    }
    //数据库操作
    if($debug === 0){
      if($mode === 2){
        $this->query("insert into $table ($sarr) values(&#39;".$set."&#39;)");
        //$return = $this->lastInsertId();
      }else if($mode === 1){
        $this->exec("insert into $table ($sarr) values(&#39;".$set."&#39;)");
        $return = $this->res;
      }else{
        $this->query("insert into $table ($sarr) values(&#39;".$set."&#39;)");
        $return = NULL;
      }
      return $return;
    }else{
      echo "insert into $table ($sarr) values(&#39;".$set."&#39;)";
      if($debug === 2){
        exit;
      }
    }
  }
  public function insert($table, $set, $debug=0, $mode=0){
    //参数处理
    if(is_array($table)){
      $table = implode(&#39;, &#39;, $table);
    }
    if(is_array($set)){
      $s=&#39;&#39;;
      foreach($set as $k=>$v){
        $s.=$k."=&#39;".$v."&#39;,";//,连接
      }
      $sarr=explode(&#39;,&#39;,$s);//去掉最后一个,
      array_pop($sarr);
      $set=implode(&#39;,&#39;,$sarr);
      //$set = implode(&#39;, &#39;, $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 数据库表,两种传值模式
  * 普通模式:
  * &#39;tb_member, tb_money&#39;
  * 数组模式:
  * array(&#39;tb_member&#39;, &#39;tb_money&#39;)
  * string/array $set 需要更新的字段及内容,两种传值模式
  * 普通模式:
  * &#39;username = "test", type = 1, dt = now()&#39;
  * 数组模式:
  * array(&#39;username = "test"&#39;, &#39;type = 1&#39;, &#39;dt = now()&#39;)
  * string/array $sqlwhere 修改条件,允许为空,两种传值模式
  * 普通模式:
  * &#39;and type = 1 and username like "%os%"&#39;
  * 数组模式:
  * array(&#39;type = 1&#39;, &#39;username like "%os%"&#39;)
  * 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(&#39;, &#39;, $table);
    }
    if(is_array($set)){
      $s=&#39;&#39;;
      foreach($set as $k=>$v){
        $s.=$k."=&#39;".$v."&#39;,";
      }
      $sarr=explode(&#39;,&#39;,$s);//去掉最后一个,
      array_pop($sarr);
      $set=implode(&#39;,&#39;,$sarr);
      //$set = implode(&#39;, &#39;, $set);
    }
    if(is_array($sqlwhere)){
      $sqlwhere = &#39; and &#39;.implode(&#39; and &#39;, $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 删除条件,允许为空,两种传值模式
  * 普通模式:
  * &#39;and type = 1 and username like "%os%"&#39;
  * 数组模式:
  * array(&#39;type = 1&#39;, &#39;username like "%os%"&#39;)
  * int $debug 是否开启调试,开启则输出sql语句
  * 0 不开启
  * 1 开启
  * 2 开启并终止程序
  * int $mode 返回类型
  * 0 无返回信息
  * 1 返回执行条目数
  */
  public function delete($table, $sqlwhere="", $debug=0, $mode=0){
    //参数处理
    if(is_array($sqlwhere)){
      $sqlwhere = &#39; and &#39;.implode(&#39; and &#39;, $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(
  &#39;dsn&#39;=>&#39;odbc:Driver={SQL Server};Server=192.168.1.60;Database=his&#39;,//数据库服务器地址
  &#39;username&#39;=>&#39;sa&#39;,
  &#39;password&#39;=>&#39;xxxxx&#39;,
);
$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(
  &#39;dsn&#39;=>&#39;mysql:host=localhost;dbname=talk&#39;,
  &#39;username&#39;=>&#39;root&#39;,
  &#39;password&#39;=>&#39;123456&#39;
);
$mysql=new PDO_DB($msyql_config);
$sql = &#39;SELECT user_id, user_name, nickname FROM et_users &#39;;
$mysql->query($sql);
$data=$mysql->fetchAll();
print_r($data);exit;
//oracle 操作
$oci_config=array(
  &#39;dsn&#39;=>&#39;oci:dbname=orcl&#39;,
  &#39;username&#39;=>&#39;BAOCRM&#39;,
  &#39;password&#39;=>&#39;BAOCRM&#39;
);
$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] => 正常
    )
)*/
?>
Copy after login

Related recommendations:

MySQL read-write separation operation implemented in PHP

PHP implements the function of preventing repeated form submission (based on token verification)

The above is the detailed content of PHP database operation class based on pdo [can support mysql, sqlserver and oracle]. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the &quot;MySQL Native Password&quot; plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

See all articles