搜尋
首頁後端開發php教程PHP PDO操作MYSQL封裝類

  1. /**
  2. * auther soulence
  3. * 呼叫資料類別檔案
  4. * modify 2015/06/12
  5. */
  6. class DBConnect
  7. {
  8. private $dbname = null;
  9. private $dodbdo = null;
  10. private $persistent = false;
  11. private $statement = null;
  12. private $lastInsID = null;
  13. private static $_instance = [];
  14. private static $_instance = [];
  15. {
  16. $this->dbname = $dbname;
  17. $this->persistent = $attr;
  18. }
  19. 公共靜態函數db ($flag='r',$persistent=false)
  20. {
  21. if(!isset($flag)){
  22. $flag = 'r';
  23. }
  24. if (!class_exists('PDO'))
  25. {
  26. throw new Exception('找不到PDO');
  27. return false;
  28. }
  29. $mysql_server = Yaf_Registry::get('mysql');
  30. if(!isset($mysql_server[$flag])){
  31. return false;
  32. }
  33. $options_arr = array(PDO::MYSQL_ATTR_INIT_COMMAND => '設定名稱'.$mysql_server[$flag]['charset'],PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC); if(Ypersed $ === true){
  34. $options_arr[PDO::ATTR_PERSISTENT] = true;
  35. }
  36. 嘗試{
  37. $pdo = new PDO($mysql_server[$flag][ '🎜> $pdo = new PDO($mysql_server_server '],$mysql_server[$flag]['使用者名稱'],$mysql_server[$flag]['password'],$options_arr);
  38. } catch (PDOException $e) {
  39. 引發新例外( $e->getMessage());
  40. //exit('連線失敗:'.$e->getMessage());
  41. 回傳 false;
  42. }
  43. if(!$pdo) {
  44. throw new Exception('PDO CONNECT ERROR');
  45. 回傳 false;
  46. }
  47. return $pdo;
  48. }
  49. /**
  50. * 得到操作資料庫物件
  51. * @param string $dbname 對應的資料庫是誰
  52. * @param bool $attr 是否長連接
  53. * return false說明給定的資料庫不存在
  54. */
  55. public static function getgetstance($dbname = ' r',$attr = false)
  56. {
  57. $mysql_server = Yaf_Registry::get('mysql');
  58. if(!isset($mysql_server[$dbname])){
  59. return false ;
  60. }
  61. $key = md5(md5($dbname.$attr,true));
  62. if (!isset(self::$_instance[$key]) || !is_object(self: :$_instance[$key] ]))
  63. self::$_instance[$key] = new self($dbname,$attr);
  64. return self::$_instance[$key];
  65. }
  66. 私有函數getConnect(){
  67. $this->pdo = self::db($this->dbname,$this->persistent);
  68. }
  69. /**
  70. * 查詢操作
  71. * @param string $sql 執行查詢的sql語句
  72. * @param array $data 查詢的條件格式為[':id'=>$id,':name'=> $name](推薦)或為[1=>$id,2=>$name]
  73. * @param bool $one 是否回傳一條內容預設為否
  74. */
  75. 公用函數查詢($sql, $data = [], $one = false)
  76. {
  77. if (!is_array($data) ||empty($sql ) || ! is_string($sql))
  78. 回傳false;
  79. $this->free();
  80. return $this->queryCommon($data,$sql,$ one) ;
  81. }
  82. /**
  83. * 內部查詢的共用方法
  84. */
  85. 乾燥函數queryCommon($data,$sql,$one)
  86. {
  87. $this->pdoExec( $ data,$sql);
  88. if ($one){
  89. return $this->statement->fetch(PDO::FETCH_ASSOC);
  90. }else{
  91. return $this ->statement->fetchAll(PDO::FETCH_ASSOC);
  92. }
  93. }
  94. /**
  95. * 多條SQL語句的查詢操作
  96. * @param array $arr_sql 執行查詢的sql語句數組格式為[$sql1,$sql2]
  97. * @param array $arr_data 查詢與$arr_sql對應的條件格式為[[':id'=>$id,':name'=>$name],[':id'=>$id,':name'=>$name]](推薦)或為[ [1=>$id,2=>$name],[1=>$id,2=>$name]]
  98. * @param bool $one 是否回傳一條內容預設為否這裡如果設定為true那麼每一條sql都只回傳一條資料
  99. */
  100. 公用函數查詢($arr_sql, $arr_data = [] , $one = false)
  101. {
  102. if(!is_array($arr_sql) ||空($arr_sql) || !is_array($arr_data))
  103. return false;
  104. $this->free();
  105. $res = [];$i = 0;
  106. foreach ( $ arr_sql as $val) {
  107. if(!isset($arr_data[$i]))
  108. $arr_data[$i] = [];
  109. elseif(!is_array($arr_data[$i]) ))
  110. throw new Exception('查詢sql時發生錯誤:'.$val.' where:'.$arr_data[$i]);
  111. $res[] = $this->queryCommon ( $arr_data[$i],$val,$one);
  112. $i ;
  113. }
  114. return $res;
  115. }
  116. /**
  117. * 分頁封裝
  118. *
  119. * @param string $sql
  120. * @param int $page 表示從第幾頁開始取
  121. * @param int $pageSize 表示每頁多少條
  122. * @param array $data 查詢的條件
  123. */
  124. public function limitQuery($sql, $page=0, $pageSize=20, $data = [])
  125. {
  126. $page = intval($page);
  127. if ($page return [];
  128. }
  129. $pageSize = intval($pageSize);
  130. if ($pageSize > 0) { // pageSize 為0時表示取得所有資料
  131. $sql .= ' LIMIT ' . $pageSize;
  132. if ($page > 0) {
  133. $start_limit = ($page - 1) * $pageSize;
  134. $sql .= ' OFFSET ' 。 > }
  135. return $this->query($sql, $data);
  136. }
  137. /**
  138. * 這個是用來進行新增刪除修改操作使用事務操作
  139. * @param string $sql 執行查詢的sql語句
  140. * @param array $data 查詢的條件格式為[':id'= >$id,':name'=>$name](推薦)或為[1=>$id,2=>$name]
  141. * @param bool $Transaction 是否交易操作預設為否
  142. */
  143. public functionexecuteDDL($sql, $data = [ ],$Transaction = false){
  144. if (!is_array($data) || !is_string($sql))
  145. return false;
  146. $this->free();
  147. if($Transaction)
  148. $this->pdo->beginTransaction();//開啟交易
  149. try{
  150. $ this->execRes($data,$sql);
  151. if($Transaction)
  152. $this->pdo->commit();//提交交易
  153. return $this->; lastInsID;
  154. } catch (Exception $e) {
  155. if($Transaction)
  156. $this->pdo->rollBack();//交易回滾
  157. throw new Exception('錯誤 DDLExecute '.$e->getMessage());
  158. return false;
  159. }
  160. }
  161. /**
  162. * 這個是用來進行新增刪除修改操作使用事務操作
  163. * 它是執行多條的
  164. * @param array $arr_sql 需要執行操作的SQL語句數組
  165. * @param array $ arr_data 與陣列對應SQL語句的條件
  166. * @param bool $Transaction 是否事務操作預設為否
  167. * /
  168. public functionexecuteDDLes($arr_sql, $arr_data = [],$Transaction = false){
  169. if(!is_array($arr_sql) || 空($arr_sql) || !is_array($ arr_data))
  170. return false;
  171. $res = [];
  172. $this->free();
  173. if($Transaction)
  174. $this->pdo-> beginTransaction();//開啟事務
  175. try{
  176. $i = 0;
  177. foreach($arr_sql as $val){
  178. if(!isset( $arr_data[$i]))
  179. $arr_data[$i] = [];
  180. elseif(!is_array($arr_data[$i])){
  181. if($Transaction)
  182. $ this->pdo->rollBack() ;// 交易回溯
  183. throw new Exception('Error where DDLExecutees sql:'.$val.' where:'.$arr_data[$i]);
  184. }
  185. $this- >execRes($arr_data[$i],$val);
  186. $res[] = $this->lastInsID;
  187. $i ;
  188. }
  189. if($Transaction)
  190. $this->pdo->commit();// 交易提交
  191. return $res;
  192. } catch (Exception $ e) {
  193. if($Transaction)
  194. $ this->pdo->rollBack();//交易回滾
  195. throw new Exception('Error DDLExecutees array_sql:'.json_encode($arr_sql) ).' '.$e->getMessage());
  196. 回傳 false;
  197. }
  198. 回傳 $res;
  199. }
  200. /**
  201. * 此方法是用來計算查詢傳回的條數注意它只支援SELECT COUNT(*) FROM TABLE...或SELECT COUNT(0) FROM TABLE...方式
  202. * @param string $sql查詢的sql語句
  203. * @param array $data SQL語句的條件
  204. */
  205. public function countRows($sql,$data = []){
  206. if (!is_array($data) ||空($sql) || !is_string($sql))
  207. return false;
  208. $this->free();
  209. $res = $this->pdoExec($data,$sql);
  210. if($res == false)
  211. return false;
  212. return $this->statement->fetchColumn();
  213. }
  214. /**
  215. * 此方法是用來計算查詢傳回的條數 它是執行多條SQL
  216. * @param string $sql 查詢的sql語句
  217. * @param array $data SQL語句的條件
  218. */
  219. public function countRowses($arr_sql,$arr_data = []){
  220. if(!is_array($arr_sql) || empempty($ arr_sql) || !is_array($arr_data))
  221. 回傳false;
  222. $res = [];
  223. $this->free();
  224. $i = 000 ;
  225. foreach ($arr_sql as $val) {
  226. if(!isset($arr_data[$i]))
  227. $arr_data[$i] = [];
  228. elseif(!is_array ( $arr_data[$i]))
  229. throw new Exception('Error where CountRowses sql:'.$val.' where:'.$arr_data[$i]);
  230. $res1 = $ this ->pdoExec($arr_data[$i],$val);
  231. if($res1 == false)
  232. $res[] = false;
  233. else
  234. $res [] = $this->statement->fetchColumn();
  235. }
  236. return $res;
  237. }
  238. /**
  239. * 這裡再提供一個方法 由於專案中會有很多需要提供開啟事務 然後再進行操作 最後提交
  240. * @param bool $Transaction 是否事務操作 預設為否
  241. */
  242. public function getDB ($Transaction=false)
  243. {
  244. $this->Transaction = $Transaction;
  245. $this->getConnect();
  246. if($Transaction === true )
  247. $this ->pdo->beginTransaction();//開啟事務
  248. return $this;
  249. }
  250. /**
  251. * 此方法可以執行多次它是執行DDL語句的
  252. * 注意它是需要配合getDB和sQCommit一起使用不能單獨使用哦
  253. * 如果沒有開啟事務sQCommit方法可以不調用
  254. * @param string $sql 查詢的sql語句
  255. * @param array $data SQL語句的條件
  256. */
  257. public function execSq($sql,$data = [])
  258. {
  259. if($this->checkParams($sql,$data) === false)
  260. return false;
  261. 嘗試{
  262. $this- >execRes($data,$sql);
  263. return $this->lastInsID;
  264. } catch (Exception $e) {
  265. if(isset($ this->Transaction) && $this->Transaction === true)
  266. $this->pdo->rollBack();//交易回滾
  267. throw new Exception('Error execSq'.$e->getMessage());
  268. return false;
  269. } 最後 {
  270. if (!empty($this->statement))
  271. {
  272. $this->statement->closeCursor();
  273. unset($this->statement);
  274. }
  275. }
  276. }
  277. /* *
  278. * 執行查詢的方法它需要傳遞一個連接資料庫物件
  279. * @param string $sql 執行查詢的sql語句
  280. * @param array $data 查詢的條件格式為[':id'=> $id,':name'=>$name](推薦)或為[1=>$id,2=>$name]
  281. * @param bool $one 是否回傳一條內容預設為否
  282. */
  283. public function querySq($sql,$data = [],$one = false)
  284. {
  285. if($this->checkParams($sql,$data) = == false)
  286. return false;
  287. return $this->pdoExecSq($sql,$data,[1,$one]);
  288. }
  289. /* *
  290. * 分頁封裝
  291. *
  292. * @param string $sql
  293. * @param int $page 表示從第幾頁開始取
  294. * @param int $pageSize 表示每頁多少條
  295. * @param array $data 查詢的條件
  296. */
  297. public function limitQuerySq($sql, $page=0, $pageSize=20, $data = [])
  298. {
  299. $page = intval($page);
  300. if ($page return [];
  301. }
  302. $pageSize = intval($pageSize);
  303. if ($pageSize > 0) { // pageSize 為0時表示取得所有資料
  304. $ sql .= '限制' 。 ;
  305. }
  306. }
  307. return $this->querySq($sql, $data);
  308. }
  309. /**
  310. * 此方法是用來計算查詢傳回的條數注意它只支援SELECT COUNT(*) FROM TABLE...或SELECT COUNT(0) FROM TABLE...方式
  311. * @param string $sql查詢的sql語句
  312. * @param array $data SQL語句的條件
  313. */
  314. 公共函數countRowsSq ($sql,$data = []){
  315. if($this->checkParams($sql,$data) === false)
  316. return false;
  317. return $this->pdoExecSq($ sql,$data,[2]);
  318. }
  319. /**
  320. * 這裡再提供一個方法 這是最後提交操作 如果沒有開啟事務 此方法最後可以不呼叫的
  321. */
  322. public function sQCommit()
  323. {
  324. if(empty($this->pdo) || !is_object($this->pdo) pdo))
  325. return false;
  326. if(isset($this->Transaction) && $this->Transaction === true)
  327. $this->pdo->commit() ;//提交事務
  328. unset($this->pdo);
  329. }
  330. /**
  331. * 內部呼叫方法
  332. */
  333. public function checkParams($sql,$data)
  334. {
  335. if ($this->pdo) || !is_object($this->pdo) || !is_array($data) || 空($sql) || !is_string($sql))
  336. 回傳false;
  337. 回傳true;
  338. }
  339. /**
  340. * 內部呼叫方法
  341. */
  342. 外部函數pdoExecSq($sql,$data,$ select = []){
  343. 嘗試{
  344. $res = $this->pdoExec($data,$sql);
  345. if(empty($select))
  346. return $res;
  347. else{
  348. if ($select[0] === 1){
  349. if($select[1] === true)
  350. return $this->statement->fetch( PDO::FETCH_ASSOC);
  351. else
  352. return $this->statement->fetchAll(PDO::FETCH_ASSOC);
  353. }elseif($select[0] === 2)
  354. return $this->statement->fetchColumn();
  355. else
  356. return false;
  357. }
  358. } catch (Exception $e) {
  359. throw new Exception($e-> ;getMessage());
  360. return false;
  361. } 最後{
  362. if (!empty($this->statement))
  363. {
  364. $this->statement->; closeCursor();
  365. unset($this->語句);
  366. }
  367. }
  368. }
  369. /**
  370. * 內部呼叫方法
  371. */
  372. 中斷函數 execRes( $資料,$sql){
  373. $res = $this->pdoExec($data,$sql);
  374. $in_id = $this->pdo->lastInsertId( );
  375. if (preg_match("/^s*(INSERTs INTO|REPLACEs INTO)s /i", $sql) && !empty($in_id))
  376. $this->lastInsID = $in_id;
  377. else
  378. $this->lastInsID = $res;
  379. }
  380. /**
  381. * 內部呼叫方法 用來直接執行SQL語句的方法
  382. */
  383. 外部函數pdoExec($data,$sql ){
  384. $ $ this->statement = $this->pdo->prepare($sql);
  385. if (false === $this->statement)
  386. return false;
  387. if (!empty($data) )
  388. {
  389. foreach ($data as $k =>; $v)
  390. {
  391. $this->語句->bindValue($k, $v);
  392. }
  393. }
  394. $res = $this->語句-> ;execute();
  395. if (!$res)
  396. {
  397. throw new Exception('sql:'.$sql.'where:'.json_encode($data ).'錯誤:'.json_encode($this->statement->errorInfo()));
  398. }else{
  399. return $res;
  400. }
  401. }
  402. /**
  403. * 內部呼叫方法 用來釋放的
  404. */
  405. 原生函數free()
  406. {
  407. if (is_null($this->pdo ))
  408. $this->getConnect();
  409. if (!empty($this->statement))
  410. {
  411. $this->statement->closeCursor();
  412. $this ->statement = null;
  413. }
  414. }
  415. }
  416. ?>
複製程式碼

PHP、PDO、MYSQL


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用數據庫存儲會話的優點是什麼?使用數據庫存儲會話的優點是什麼?Apr 24, 2025 am 12:16 AM

使用數據庫存儲會話的主要優勢包括持久性、可擴展性和安全性。 1.持久性:即使服務器重啟,會話數據也能保持不變。 2.可擴展性:適用於分佈式系統,確保會話數據在多服務器間同步。 3.安全性:數據庫提供加密存儲,保護敏感信息。

您如何在PHP中實現自定義會話處理?您如何在PHP中實現自定義會話處理?Apr 24, 2025 am 12:16 AM

在PHP中實現自定義會話處理可以通過實現SessionHandlerInterface接口來完成。具體步驟包括:1)創建實現SessionHandlerInterface的類,如CustomSessionHandler;2)重寫接口中的方法(如open,close,read,write,destroy,gc)來定義會話數據的生命週期和存儲方式;3)在PHP腳本中註冊自定義會話處理器並啟動會話。這樣可以將數據存儲在MySQL、Redis等介質中,提升性能、安全性和可擴展性。

什麼是會話ID?什麼是會話ID?Apr 24, 2025 am 12:13 AM

SessionID是網絡應用程序中用來跟踪用戶會話狀態的機制。 1.它是一個隨機生成的字符串,用於在用戶與服務器之間的多次交互中保持用戶的身份信息。 2.服務器生成並通過cookie或URL參數發送給客戶端,幫助在用戶的多次請求中識別和關聯這些請求。 3.生成通常使用隨機算法保證唯一性和不可預測性。 4.在實際開發中,可以使用內存數據庫如Redis來存儲session數據,提升性能和安全性。

您如何在無狀態環境(例如API)中處理會議?您如何在無狀態環境(例如API)中處理會議?Apr 24, 2025 am 12:12 AM

在無狀態環境如API中管理會話可以通過使用JWT或cookies來實現。 1.JWT適合無狀態和可擴展性,但大數據時體積大。 2.Cookies更傳統且易實現,但需謹慎配置以確保安全性。

您如何防止與會議有關的跨站點腳本(XSS)攻擊?您如何防止與會議有關的跨站點腳本(XSS)攻擊?Apr 23, 2025 am 12:16 AM

要保護應用免受與會話相關的XSS攻擊,需採取以下措施:1.設置HttpOnly和Secure標誌保護會話cookie。 2.對所有用戶輸入進行輸出編碼。 3.實施內容安全策略(CSP)限制腳本來源。通過這些策略,可以有效防護會話相關的XSS攻擊,確保用戶數據安全。

您如何優化PHP會話性能?您如何優化PHP會話性能?Apr 23, 2025 am 12:13 AM

优化PHP会话性能的方法包括:1.延迟会话启动,2.使用数据库存储会话,3.压缩会话数据,4.管理会话生命周期,5.实现会话共享。这些策略能显著提升应用在高并发环境下的效率。

什麼是session.gc_maxlifetime配置設置?什麼是session.gc_maxlifetime配置設置?Apr 23, 2025 am 12:10 AM

theSession.gc_maxlifetimesettinginphpdeterminesthelifespanofsessiondata,setInSeconds.1)它'sconfiguredinphp.iniorviaini_set().2)abalanceisesneededeededeedeedeededto toavoidperformance andunununununexpectedLogOgouts.3)

您如何在PHP中配置會話名?您如何在PHP中配置會話名?Apr 23, 2025 am 12:08 AM

在PHP中,可以使用session_name()函數配置會話名稱。具體步驟如下:1.使用session_name()函數設置會話名稱,例如session_name("my_session")。 2.在設置會話名稱後,調用session_start()啟動會話。配置會話名稱可以避免多應用間的會話數據衝突,並增強安全性,但需注意會話名稱的唯一性、安全性、長度和設置時機。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),