zoukankan      html  css  js  c++  java
  • 封装PDO连接数据库代码

    废话不说直接上代码:

      1 <?php
      2 class DB
      3 {
      4     protected static $_connect;
      5     protected $dsn, $pdo;
      6     protected $_data, $_count, $_lastInsertId;
      7   
      8     /**
      9      * 构造函数
     10      * 
     11      * @return DB
     12      */
     13     private function __construct($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset, $dbms)
     14     {
     15         try {
     16             $this->dsn = $dbms.':host='.$dbHost.';dbname='.$dbName;
     17             $this->pdo = new PDO($this->dsn, $dbUser, $dbPasswd);
     18             $this->pdo->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');
     19         } catch (PDOException $e) {
     20             $this->outputError($e->getMessage());
     21         }
     22     }
     23 
     24     /**
     25      * 获取返回结果、行数及最新插入数据的id
     26      * 
     27      */
     28     public function data(){
     29         return $this->_data;
     30     }
     31     public function count(){
     32         return $this->_count;
     33     }
     34     public function lastInsertId(){
     35         return $this->_lastInsertId;
     36     }
     37 
     38     /**
     39      * 防止克隆
     40      * 
     41      */
     42     private function __clone() {}
     43 
     44     /**
     45      * Singleton instance
     46      * 
     47      * @return Object
     48      */
     49     public static function connect($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset="utf8", $dbms="mysql")
     50     {
     51         if (self::$_connect === null) {
     52             self::$_connect = new self($dbHost, $dbUser, $dbPasswd, $dbName, $dbCharset, $dbms);
     53         }
     54         return self::$_connect;
     55     }
     56 
     57 
     58     /**
     59      * Go 增删改查覆盖
     60      * 
     61      * @param String $strSql SQL语句
     62      * @param Array $arrayInputValue 替换占位符的值
     63      * @return Object
     64      */
     65     public function go($strSql, $arrayInputValue){
     66         $handle=strtolower(preg_split("/s+/",$strSql)[0]);//----获取sql语句第一个词(可能是select、update、delete、insert或replace)
     67         if(strpos("/insert/delete/update/select/replace",$handle)>0){
     68             $stmt = $this->pdo->prepare($strSql);
     69             $stmt->execute($arrayInputValue);
     70             $this->getPDOError();
     71             $this->_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
     72             $this->_count=$stmt->rowCount();// ----如果是覆盖旧数据,rowCount不准确
     73             $this->_lastInsertId=$this->pdo->lastInsertId();
     74             return $this;
     75         }else{
     76             echo "<br>请检查sql语句是否有误!<br>";
     77         }
     78     }
     79 
     80     /**
     81      * execSql
     82      *
     83      * @param String $strSql
     84      * @return Int
     85      */
     86     public function execSql($strSql)
     87     {
     88         $result = $this->pdo->exec($strSql);
     89         $this->getPDOError();
     90         return $result;
     91     }
     92 
     93     /**
     94      * 获取字段最大值
     95      * 
     96      * @param string $table 表名
     97      * @param string $field_name 字段名
     98      * @param string $where 条件
     99      */
    100     public function getMaxValue($table, $field_name, $where = '')
    101     {
    102         $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
    103         if ($where != '') $strSql .= " WHERE $where";
    104         $stmt = $this->pdo->prepare($strSql);
    105         $stmt->execute();
    106         $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    107         $maxValue = $data[0]["MAX_VALUE"];
    108         if ($maxValue == "" || $maxValue == null) {
    109             $maxValue = 0;
    110         }
    111         return $maxValue;
    112     }
    113 
    114     /**
    115      * 获取指定列的数量
    116      * 
    117      * @param string $table
    118      * @param string $field_name
    119      * @param string $where
    120      * @return int
    121      */
    122     public function getCount($table, $field_name, $where = '')
    123     {
    124         $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
    125         if ($where != '') $strSql .= " WHERE $where";
    126         $stmt = $this->pdo->prepare($strSql);
    127         $stmt->execute();
    128         $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    129         return $data[0]["NUM"];
    130     }
    131 
    132     /**
    133      * 获取指定列的总和
    134      * 
    135      * @param string $table
    136      * @param string $field_name
    137      * @param string $where
    138      * @return int
    139      */
    140     public function getSum($table, $field_name, $where = '')
    141     {
    142         $strSql = "SELECT SUM($field_name) AS SN FROM $table";
    143         if ($where != '') $strSql .= " WHERE $where";
    144         $stmt = $this->pdo->prepare($strSql);
    145         $stmt->execute();
    146         $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    147         return $data[0]["SN"];
    148     }
    149 
    150     /**
    151    * 预处理执行
    152    */
    153     public function prepareSql($sql=''){
    154         return $this->pdo->prepare($sql);
    155   }
    156   
    157     /**
    158    * 执行预处理
    159    */
    160     public function execute($presql){
    161         return $this->pdo->execute($presql);
    162     }
    163 
    164     /**
    165      * pdo属性设置
    166      */
    167     public function setAttribute($p,$d){
    168         $this->pdo->setAttribute($p,$d);
    169     }
    170 
    171     /**
    172      * beginTransaction 事务开始
    173      */
    174     public function beginTransaction()
    175     {
    176         $this->pdo->beginTransaction();
    177     }
    178 
    179     /**
    180      * commit 事务提交
    181      */
    182     public function commit()
    183     {
    184         $this->pdo->commit();
    185     }
    186 
    187     /**
    188      * rollback 事务回滚
    189      */
    190     public function rollback()
    191     {
    192         $this->pdo->rollback();
    193     }
    194 
    195     /**
    196      * getPDOError 捕获PDO错误信息
    197      */
    198     private function getPDOError()
    199     {
    200         if ($this->pdo->errorCode() != '00000') {
    201             $arrayError = $this->pdo->errorInfo();
    202             $this->outputError($arrayError[2]);
    203         }
    204     }
    205 
    206     /**
    207      * 输出错误信息
    208      * 
    209      * @param String $strErrMsg
    210      */
    211     private function outputError($strErrMsg)
    212     {
    213         throw new Exception('MySQL Error: '.$strErrMsg);
    214     }
    215 
    216     /**
    217      * 关闭数据库连接
    218      */
    219     public function close()
    220     {
    221         $this->pdo = null;
    222     }
    223 }
    224 ?>

    如何使用:

    <?php
    require "db.class.php";//----引入文件
    $pdo=DB::connect("localhost","root","[密码]","[数据库名]");//--创建PDO并连接数据库
    $sql="……";//----注:这里sql语句占位符必须用“?”表示
    $pdo->go($sql, array("[value1]","[value2]",...));//---执行sql语句(所有sql语句均可用go函数执行)
    
    var_dump($pdo->result());//----打印结果集(如果是select语句返回的是代表结果集的数组,如果是其他语句返回的是空数组)
    echo $pdo->count();//-----如果是select打印的是结果集包含的数据数量,如果是delete或update打印的是删除或更改的数据数量
    echo $pdo->lastInsertId();//------如果是insert语句,$pdo->lastInsertId()表示最新插入数据的id
    
    $pdo->close();//----关闭连接
    ?>
  • 相关阅读:
    Ynoi 杂题选做
    CSP-S2021 浙江 游记
    P6272 [湖北省队互测2014]没有人的算术
    P5206 [WC2019]数树
    P5405 [CTS2019]氪金手游
    LOJ6679 Unknow
    LOJ3040 「JOISC 2019 Day4」合并
    P6122 [NEERC2016]Mole Tunnels
    三维凸包
    三,四元环计数
  • 原文地址:https://www.cnblogs.com/programs/p/9500736.html
Copyright © 2011-2022 走看看