搜尋
首頁後端開發php教程超輕量的 PHP 資料庫工具包

複製程式碼
一個很輕的 PHP 資料庫工具包,誕生時間兩天(足以證明很輕了 )。
兩個類,一個 Connection 管理 PDO 連線(支援多資料庫),一個 QuickQuery 用來快速執行資料庫操作(不用在 PDO 和 PDOStatement 之間來回折騰)
不用下載,線上就能看完。
  1. use PersistenceDbAccess;
  2. // 在框架初始化的地方加入連線資訊
  3. DbAccessConnection::add(
  4. 'default',
  5. ' sqlite',
  6. '/db/mydb.sqlite',
  7. null, null, false
  8. );
  9. // 下面是使用
  10. $conn = DbAccessConnection::instance( 'default');
  11. // 查詢
  12. $query = new DbAccessQuickQuery($conn);
  13. $query->prepare('select :name as name')->execute(array( ':name'=>'tonyseek'));
  14. // 物件直接作為迭代器產生資料數組
  15. foreach($query as $i) {
  16. var_dump($i);
  17. }
  18. // 如果有偏執的話,輸出回應之前手動斷開連接
  19. DbAccessConnection::disconnectAll();
複製程式碼
複製程式碼複製程式碼複製程式碼
  1. namespace PersistenceDbAccess;
  2. use PDO, ArrayObject, DateTime;
  3. use LogicException, InvalidArgumentException;
  4. use LogicException, InvalidArgumentException; >*/
  5. class QuickQuery implements IteratorAggregate
  6. {
  7. /**
  8. * 快速查詢頻道
  9. *
  10. * @version 0.3
  11. * @author tonyseek
  12. * @link http://stu.szu.edu.cn
  13. * @license http: //www.opensource.org/licenses/mit-license.html
  14. * @copyright StuCampus Development Team, Shenzhen University
  15. *
  16. */
  17. private $connection = null;
  18. /
  19. * 資料庫連線
  20. *
  21. * @var PersistenceDbAccessConnection
  22. > private $stmt = null;
  23. /**
  24. * PDO 語句
  25. *
  26. * @var PDOStatement
  27. */
  28. private $checkedParams = array();
  29. /**
  30. * 被檢查參數集
  31. *
  32. * @var array
  33. *
  34. * 建構查詢通道
  35. *
  36. * @param PersistenceDbAccessConnection $connection 資料庫連線
  37. *
  38. public function __construct(Connection $connection)
  39. {
  40. $this->connection = $connection;
  41. }
  42. /**
  43. * 預先編譯 SQL 語句
  44. *
  45. * @param string $sqlCommand SQL語句
  46. * @return PersistenceDbAccessQuickQuery
  47. */
  48. publicunc. ($sqlCommand)
  49. {
  50. // 從連線取得PDO, 並對SQL 語句執行prepare, 產生PDO Statement
  51. $this->stmt = $this->connection->getPDO()->prepare ($sqlCommand);
  52. // 修改PDO Statement 模式為關聯數組資料
  53. $this->stmt->setFetchMode(PDO::FETCH_ASSOC);
  54. // 傳回方法鏈
  55. return $this ;
  56. }
  57. /**
  58. * 執行資料查詢
  59. *
  60. * @throws PDOException
  61. * @return PersistenceDbAccessQuickQuery
  62. */
  63. public function execute($params = array())
  64. {
  65. $stmt = $this->getStatement() ;
  66. // 參數檢查
  67. $diff = array_diff($this->checkedParams, array_keys($params));
  68. if (count($this->checkedParams) && count($diff )) {
  69. throw new InvalidArgumentException('缺少必備參數:'.implode(' | ', $diff));
  70. }
  71. // 將PHP 資料型別對應到資料庫資料型態
  72. foreach($params as $key => $value) {
  73. $type = null;
  74. switch(true) {
  75. case is_int($value):
  76. $type = PDO: :PARAM_INT;
  77. break;
  78. case is_bool($value):
  79. $type = PDO::PARAM_BOOL;
  80. break;
  81. case ($value instanceof DateTime): $value = $value->format(DateTime::W3C);
  82. break;
  83. case is_null($value):
  84. $type = PDO::PARAM_NULL;
  85. break;
  86. default:
  87. $type = PDO::PARAM_STR;
  88. }
  89. $stmt->bindValue($key, $value, $type);
  90. $stmt->bindValue($key, $value, $type);
  91. }
  92. $stmt->execute();
  93. $this->checkedParams = array(); // 清空參數檢定
  94. return $this;
  95. }
  96. /**
  97. * 取得 Statement 物件
  98. *
  99. * 傳回物件可以被綁定參數重新執行, 也可以被當作迭代器遍歷取得資料。
  100. *
  101. * @return PDOStatement
  102. */
  103. public function getStatement()
  104. {
  105. if (!$this->stmt) {
  106. throw new LogicException('''pSQL處理');
  107. }
  108. return $this->stmt;
  109. }
  110. /**
  111. * getStatement 方法的替代名稱
  112. *
  113. * 實作 PHP 標準函式庫 中的 IteratorAggregate 介面, 外部可以直接將本物件作為迭代器遍
  114. * 歷。和 getStatment 唯一不同之處, 是本方法不會拋出 LogicException 例外。如果
  115. * 沒有事先使用 prepare 和 execute, 會回傳一個空迭代器。
  116. *
  117. * @return Traversable
  118. */
  119. public function getIterator()*/
  120. public function getIterator() {
  121. try {
  122. return $this->getStatement();
  123. } catch (LogicException $ex) {
  124. return new ArrayObject();
  125. }
  126. }
  127. /**
  128. * 設定查詢參數檢查
  129. *
  130. * 透過此處匯入的被檢查查詢​​參數, 如果沒有得到賦值, 則查詢時會拋出LogicException 例外。
  131. *
  132. * @param array $params
  133. * @return PersistenceDbAccessQuickQuery
  134. */
  135. public function setParamsCheck(array $params)
  136. return $this;
  137. }
  138. /**
  139. * 將結果集轉換為陣列
  140. *
  141. * @return array
  142. */
  143. public function toArray()
  144. {
  145. return iterator_this_array($ ->getStatement());
  146. }
  147. /**
  148. * 取得最後一個插入結果(或序列)的 ID
  149. *
  150. * @param string $name
  151. * @return int
  152. */
  153. public function getLastInsertId($name=null)
  154. {
  155. return $this->connection $this->connection ->getPDO()->lastInsertId($name);
  156. }
  157. }
複製程式碼
  1. namespace PersistenceDbAccess;
  2. use InvalidArgumentException, BadMethodCallException;
  3. >**Exception; *
  4. * @version 0.3
  5. * @author tonyseek
  6. * @link http://stu.szu.edu.cn
  7. * @license http://www.opensource.org /licenses/mit-license.html
  8. * @copyright 深圳大學StuCampus 開發團隊
  9. *
  10. */
  11. 期末班連接
  12. {
  13. /**
  14. * Connector 實例集合
  15. *
  16. * @var array
  17. */
  18. static private $instances = array();
  19. /**
  20. * 資料庫驅動名稱
  21. *
  22. * @var string
  23. */
  24. private $driver = '';
  25. /**
  26. * 資料庫連接字串(Database Source Name)
  27. *
  28. * @var string
  29. */
  30. * PDO 實例
  31. *
  32. * @var PDO
  33. * 🎜> private $dsn = '';
  34. /**
  35. * 使用者名稱
  36. *
  37. * @var string
  38. */
  39. private $pdo = null;
  40. /**
  41. * 密碼
  42. *
  43. * @var string
  44. */
  45. 私人$使用者名稱= '';
  46. /**
  47. * 是否開啟持久連線
  48. *
  49. * @var bool
  50. */
  51. 私人$密碼= '';
  52. /**
  53. * 是否開啟模擬預編譯
  54. *
  55. * @var bool
  56. */
  57. 私人$ isPersisten = false;
  58. /**
  59. * 是否在交易中
  60. *
  61. * @var bool
  62. */
  63. private $isEmulate = false;
  64. /**
  65. * 私有建構函數,阻止外部使用 new 運算子實例化
  66. */
  67. private $isalation
  68. /**
  69. * 生產 Connector 實例(多例)
  70. *
  71. * @param string $name
  72. * @return StuCampusDataModelConnector
  73. */
  74. private function __construct(){}
  75. /**
  76. * 中斷所有資料庫實例的連線
  77. */
  78. static public function getgetstance($name = ' default')
  79. {
  80. if (!isset(self::$instances[$name])) {
  81. // 存取的實例不存在則發送錯誤異常
  82. throw new InvalidArgumentException( 如果" [{$name}] 不存在");
  83. }
  84. return self::$instances[$name];
  85. }
  86. /**
  87. * 新增資料庫
  88. *
  89. * 在實例群組中加入Connector
  90. *
  91. * @param string $name 識別名稱
  92. * @param string $driver 驅動名
  93. * @ param string $dsn 連接字串
  94. * @param string $usr 資料庫使用者名稱
  95. * @param string $pwd 資料庫密碼
  96. * @param bool $emulate 模擬預編譯查詢
  97. * @param bool $persisten 是否持久連接
  98. * /
  99. static public functiondetachAll()
  100. {
  101. foreach (self::$instances as $instance) {
  102. $instance->disconnect();
  103. }
  104. }
  105. }
  106. 🎜> /**
  107. * 取得 PHP Database Object
  108. *
  109. * @return PDO
  110. */
  111. 靜態公用函數登錄($name, $driver, $dsn, $usr, $pwd, $emulate = false, $persisten = false)
  112. {
  113. {
  114. if (isset(self::$instances[$name])) {
  115. // 如果新增的實例名已經存在則發送例外狀況
  116. throw new BadMethodCallException("[{$name}] 已註冊" );
  117. }
  118. // 實例化自身,並推入倉庫中
  119. self::$instances[$name] = new self();
  120. self:: $instances[ $name]->dsn = $driver 。 ':'。 $dsn;
  121. self::$instances[$name]->使用者名稱= $usr;
  122. self::$instances[$name]->password = $pwd;
  123. self::$ instances [$name]->driver = $driver;
  124. self::$instances[$name]->isPersisten = (bool)$persisten;
  125. self::$instances[$name]-> ;isEmulate = (bool)$emulate;
  126. }
  127. /**
  128. * 取得資料庫驅動名稱
  129. *
  130. * @return string
  131. */
  132. public function getPDO()
  133. {
  134. if (!$this-> pdo) {
  135. // 檢查PDO 是否已經實例化,否則先實例化PDO
  136. $this->pdo = new PDO($this->dsn, $this->username, $this- >password);
  137. // 錯誤模式為傳送PDOException 例外
  138. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  139. // 開啟查詢佇列
  140. $this->pdo->setAttribute->setAttribute->setAttribute->setAttribute->setAttribute->setAttrib 。 > }
  141. return $this->pdo;
  142. }
  143. /**
  144. * 開始事務
  145. * /
  146. public function getDriverName()
  147. {
  148. return $ this->driver;
  149. }
  150. /**
  151. * 提交交易
  152. */
  153. public function transationBegin()
  154. {
  155. $this->isInTransation = $this->getPDO( )->beginTransaction();
  156. }
  157. /**
  158. * 回滾事務
  159. * @return bool
  160. */
  161. public function transationCommit()
  162. {
  163. if ($this->isInTransation) {
  164. $this->getPDO()->commit();
  165. } else {
  166. trigger_error ('transationBegin 應該先於transationCommit 呼叫');
  167. }
  168. }
  169. /***/
  170. public function transationRollback()
  171. {
  172. if ( $this->isInTransation) {
  173. $this->getPDO()->rollBack();
  174. } else {
  175. trigger_error('transationBegin 應該先於transationRollback 呼叫');
  176. }
  177. }
  178. /**
  179. * 連線是否在交易中
  180. *
  181. * @return bool
  182. */
  183. public function isInTransation()
  184. {
  185. return $this->isInTransation;
  186. }
  187. /
  188. * 在交易中執行回呼函數
  189. *
  190. * @param function $callback 匿名函數或閉包函數
  191. * @param bool $autoRollback 異常發生時是否自動回滾
  192. * @param bool $autoRollback 異常發生時是否自動回滾
  193. * @ throws PDOException
  194. * @return bool
  195. */
  196. public function transationExecute($callback, $autoRollback = true)
  197. {
  198. try {
  199. // 開始交易
  200. $this->transationBegin();
  201. // 開始交易
  202. $this->transationBegin();
  203. / 呼叫回呼函數
  204. if (is_callable($callback)) {
  205. $callback();
  206. } else {
  207. throw new InvalidArgumentException('$callback應該為回呼函數}
  208. // 提交事務
  209. return $this->transationCommit();
  210. } catch(PDOException $pex) {
  211. // 如果開啟了自動回滾, 則捕捉到PDO 異常時先回滾再拋出
  212. if ($autoRollback) {
  213. $this->transationRollback();
  214. }
  215. throw $pex;
  216. }
  217. }
  218. /**
  219. * 安全地斷開資料庫連線
  220. */
  221. public function disconnect()
  222. {
  223. if ($this->pdo) {
  224. // 檢查PDO 是否已經實例化,是則設為null
  225. $this->pdo = null;
  226. }
  227. }
  228. /**
  229. * 阻止複製
  230. */
  231. public function __clone()
  232. {
trigger_error('被封鎖的__clone 方法, Connector 是單例類別');
}}


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
可以在PHP會話中存儲哪些數據?可以在PHP會話中存儲哪些數據?May 02, 2025 am 12:17 AM

phpsessionscanStorestrings,數字,數組和原始物。

您如何開始PHP會話?您如何開始PHP會話?May 02, 2025 am 12:16 AM

tostartaphpsession,usesesses_start()attheScript'Sbeginning.1)placeitbeforeanyOutputtosetThesessionCookie.2)useSessionsforuserDatalikeloginstatusorshoppingcarts.3)regenerateSessiveIdStopreventFentfixationAttacks.s.4)考慮使用AttActAcks.s.s.4)

什麼是會話再生,如何提高安全性?什麼是會話再生,如何提高安全性?May 02, 2025 am 12:15 AM

會話再生是指在用戶進行敏感操作時生成新會話ID並使舊ID失效,以防會話固定攻擊。實現步驟包括:1.檢測敏感操作,2.生成新會話ID,3.銷毀舊會話ID,4.更新用戶端會話信息。

使用PHP會話時有哪些性能考慮?使用PHP會話時有哪些性能考慮?May 02, 2025 am 12:11 AM

PHP会话对应用性能有显著影响。优化方法包括:1.使用数据库存储会话数据,提升响应速度;2.减少会话数据使用,只存储必要信息;3.采用非阻塞会话处理器,提高并发能力;4.调整会话过期时间,平衡用户体验和服务器负担;5.使用持久会话,减少数据读写次数。

PHP會話與Cookie有何不同?PHP會話與Cookie有何不同?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

PHP如何識別用戶的會話?PHP如何識別用戶的會話?May 01, 2025 am 12:23 AM

phpIdentifiesauser'ssessionSessionSessionCookiesAndSessionId.1)whiwsession_start()被稱為,phpgeneratesainiquesesesessionIdStoredInacookInAcookInAcienamedInAcienamedphpsessIdontheuser'sbrowser'sbrowser.2)thisIdallowSphptpptpptpptpptpptpptpptoretoreteretrieetrieetrieetrieetrieetrieetreetrieetrieetrieetrieetremthafromtheserver。

確保PHP會議的一些最佳實踐是什麼?確保PHP會議的一些最佳實踐是什麼?May 01, 2025 am 12:22 AM

PHP會話的安全可以通過以下措施實現:1.使用session_regenerate_id()在用戶登錄或重要操作時重新生成會話ID。 2.通過HTTPS協議加密傳輸會話ID。 3.使用session_save_path()指定安全目錄存儲會話數據,並正確設置權限。

PHP會話文件默認存儲在哪裡?PHP會話文件默認存儲在哪裡?May 01, 2025 am 12:15 AM

phpsessionFilesArestoredIntheDirectorySpecifiedBysession.save_path,通常是/tmponunix-likesystemsorc:\ windows \ windows \ temponwindows.tocustomizethis:tocustomizEthis:1)useession_save_save_save_path_path()

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

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

熱工具

mPDF

mPDF

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

MantisBT

MantisBT

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

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