Home Backend Development PHP Tutorial php pdo encapsulation class code (supports transactions)

php pdo encapsulation class code (supports transactions)

Jul 25, 2016 am 08:51 AM

  1. /**
  2. * PDO database
  3. * @copyright By GOOGLE
  4. */
  5. class pdo_db
  6. {
  7. /**
  8. * PDO instance
  9. * @var PDO
  10. */
  11. protected $_db;
  12. /**
  13. * PDO prepared statement
  14. * @var PDOStatement
  15. */
  16. protected $_stmt;
  17. /**
  18. * Last SQL statement
  19. * @var string
  20. */
  21. protected $_sql;
  22. /**
  23. * Configuration information $config=array('dsn'=>xxx,'name'=>xxx,'password'=>xxx,'option'=>xxx)
  24. * @var array
  25. */
  26. protected $_config;
  27. /**
  28. * Constructor
  29. * @param array $config
  30. */
  31. public function __construct($config)
  32. {
  33. $this->_config = $config;
  34. }
  35. /**
  36. * Connect to database
  37. * @return void
  38. */
  39. public function connect()
  40. {
  41. $this->_db = new PDO($this->_config['dsn'], $this->_config['name'], $this->_config['password'], $this->_config['option']);
  42. //默认把结果序列化成stdClass
  43. // $this->_db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
  44. $this->_db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  45. //自己写代码捕获Exception
  46. $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
  47. }
  48. /**
  49. * Disconnect
  50. * @return void
  51. */
  52. public function disConnect()
  53. {
  54. $this->_db = null;
  55. $this->_stmt = null;
  56. }
  57. /**
  58. * Execute sql and return the newly added id
  59. * @param string $statement
  60. * @return string
  61. */
  62. public function exec($statement)
  63. {
  64. if ($this->_db->exec($statement)){
  65. $this->_sql = $statement;
  66. return $this->lastId();
  67. }
  68. $this->errorMessage();
  69. }
  70. /**
  71. * Query sql
  72. * @param string $statement
  73. * @return pdo_db
  74. */
  75. public function query($statement)
  76. {
  77. $res = $this->_db->query($statement);
  78. if ($res){
  79. $this->_stmt = $res;
  80. $this->_sql = $statement;
  81. return $this;
  82. }
  83. $this->errorMessage();
  84. }
  85. /**
  86. * Serialize data once
  87. * @return mixed
  88. */
  89. public function fetchOne()
  90. {
  91. return $this->_stmt->fetch();
  92. }
  93. /**
  94. * Serialize all data
  95. * @return array
  96. */
  97. public function fetchAll()
  98. {
  99. return $this->_stmt->fetchAll();
  100. }
  101. /**
  102. * Last added id
  103. * @return string
  104. */
  105. public function lastId()
  106. {
  107. return $this->_db->lastInsertId();
  108. }
  109. /**
  110. * Number of rows affected
  111. * @return int
  112. */
  113. public function affectRows()
  114. {
  115. return $this->_stmt->rowCount();
  116. }
  117. /**
  118. * prepared statement
  119. * @param string $statement
  120. * @return pdo_db
  121. */
  122. public function prepare($statement)
  123. {
  124. $res = $this->_db->prepare($statement);
  125. if ($res){
  126. $this->_stmt = $res;
  127. $this->_sql = $statement;
  128. return $this;
  129. }
  130. $this->errorMessage();
  131. }
  132. /**
  133. * Bind data
  134. * @param array $array
  135. * @return pdo_db
  136. */
  137. public function bindArray($array)
  138. {
  139. foreach ($array as $k => $v){
  140. if (is_array($v)){
  141. //array的有效结构 array('value'=>xxx,'type'=>PDO::PARAM_XXX)
  142. $this->_stmt->bindValue($k + 1, $v['value'], $v['type']);
  143. } else{
  144. $this->_stmt->bindValue($k + 1, $v, PDO::PARAM_STR);
  145. }
  146. }
  147. return $this;
  148. }
  149. /**
  150. * Execute prepared statements
  151. * @return bool
  152. */
  153. public function execute()
  154. {
  155. if ($this->_stmt->execute()){
  156. return true;
  157. }
  158. $this->errorMessage();
  159. }
  160. /**
  161. * Start transaction
  162. * @return bool
  163. */
  164. public function beginTransaction()
  165. {
  166. return $this->_db->beginTransaction();
  167. }
  168. /**
  169. * Execute transaction
  170. * @return bool
  171. */
  172. public function commitTransaction()
  173. {
  174. return $this->_db->commit();
  175. }
  176. /**
  177. * Rollback transaction
  178. * @return bool
  179. */
  180. public function rollbackTransaction()
  181. {
  182. return $this->_db->rollBack();
  183. }
  184. /**
  185. * Throws Error
  186. * @throws Error
  187. * @return void
  188. */
  189. public function errorMessage()
  190. {
  191. return;
  192. $msg = $this->_db->errorInfo();
  193. throw new Exception('数据库错误:' . $msg[2]);
  194. }
  195. //---------------------
  196. /**
  197. * Singleton instance
  198. * @var pdo_db
  199. */
  200. protected static $_instance;
  201. /**
  202. * Default database
  203. * @static
  204. * @param array $config
  205. * @return pdo_db
  206. */
  207. public static function instance($config)
  208. {
  209. if (!self::$_instance instanceof pdo_db){
  210. self::$_instance = new pdo_db($config);
  211. self::$_instance->connect();
  212. }
  213. return self::$_instance;
  214. }
  215. //----------------------
  216. /**
  217. * Get the database supported by PDO
  218. * @static
  219. * @return array
  220. */
  221. public static function getSupportDriver(){
  222. return PDO::getAvailableDrivers();
  223. }
  224. /**
  225. * Get the version information of the database
  226. * @return array
  227. */
  228. public function getDriverVersion(){
  229. $name = $this->_db->getAttribute(PDO::ATTR_DRIVER_NAME);
  230. return array($name=>$this->_db->getAttribute(PDO::ATTR_CLIENT_VERSION));
  231. }
  232. }
复制代码


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles