封裝PDO鏈接數據庫代碼

廢話不說直接上代碼:php

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

 

如何使用:mysql

 

<?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();//----關閉鏈接
?>
相關文章
相關標籤/搜索