Home Backend Development PHP Tutorial PHP PDO encapsulated static class code sharing

PHP PDO encapsulated static class code sharing

Jul 25, 2016 am 08:51 AM

  1. /**
  2. * Class DB
  3. * Database operation class
  4. */
  5. class DB {
  6. /**
  7. * @var
  8. * @return CDB
  9. */
  10. private static $db;
  11. /**Get CDb class
  12. * @param $table_name table name
  13. * @param string $db_setting call database configuration item
  14. * @param array $db_config database configuration
  15. * @return CDb
  16. */
  17. public static function cdb($table_name='',$db_setting='default',$db_config=array()){
  18. if(!isset(self::$db)){
  19. $db = new CDb($table_name,$db_setting, $db_config);
  20. self::$db=$db;
  21. }else{
  22. $db=self::$db;
  23. }
  24. return $db;
  25. }
  26. /**Configuration
  27. * @param $table_name table name
  28. * @param string $db_setting Call database configuration item
  29. * @param array $db_config database configuration
  30. * @return CDb
  31. */
  32. public static function init($table_name='',$db_setting='default',$db_config=array()) {
  33. return self::cdb($table_name,$db_setting,$db_config);
  34. }
  35. /**
  36. * Execute deletion record operation
  37. * @param $table table name
  38. * @param $condition Delete data condition, not allowed to be empty. Can be an array
  39. * @return boolean
  40. * /
  41. public static function delete($table, $condition) {
  42. $db=self::cdb();
  43. $db->setTableName($table);
  44. return $db->delete($condition);
  45. }
  46. /**
  47. * Execute adding record operation
  48. * @param $table table name
  49. * @param array $data The data to be added, the parameter is an array.The array key is the field value, and the array value is the data value
  50. * @param bool $return_insert_id Whether to return the new ID number
  51. * @param bool $replace Whether to add data by replace into
  52. * @return boolean
  53. */
  54. public static function insert($table, $data, $return_insert_id = false, $replace = false) {
  55. $db=self::cdb();
  56. $db->setTableName($table);
  57. return $db-> insert($data, $return_insert_id, $replace);
  58. }
  59. /**
  60. * Get the primary key number of the last added record
  61. * @return int
  62. */
  63. public static function insertID() {
  64. $db=self::cdb();
  65. return $db->insert_id ();
  66. }
  67. /**
  68. * Execute update record operation
  69. * @param $table table name
  70. * @param $data The data content to be updated, the parameter is an array
  71. * When it is an array, the array key is the field value, and the array value is the data value
  72. * When it is an array [Example: array('name'=>'lanmps','password'=>'123456')]
  73. * Another way to use array array('name'=>'+=1', ' base'=>'-=1');The program will automatically parse as `name` = `name` + 1, `base` = `base` - 1
  74. * string, please follow the format:
  75. * string[ Example 2: array('catid=:catid AND time>=:time ',array(':catid'=>10,':time'=>'2012-02-10')) ]
  76. * @param $where conditions for updating data,
  77. * string, please follow the format:
  78. * string [Example 1: " id=1 and time>$time " ]
  79. * string [Example 2: array('catid=: catid AND time>=:time ',array(':catid'=>10,':time'=>'2012-02-10')) ]
  80. * Array [Example: array('name'= >'lanmps','password'=>'123456')]
  81. * @return boolean
  82. */ bbs.it-home.org
  83. public static function update($table, $data, $where) {
  84. $db=self::cdb();
  85. $ db->setTableName($table);
  86. return $db->update($data,$where);
  87. }
  88. /**
  89. * Get single record query
  90. * @param array $sql query condition statement
  91. * @return array/null data query result set, if it does not exist, return empty
  92. */
  93. public static function fetchFirst($sql) {
  94. $db =self::cdb();
  95. return $db->fetch($sql);
  96. }
  97. /**
  98. * Execute sql query
  99. * @param $sql query conditions
  100. * @return array Query result set array
  101. */
  102. public static function fetchAll($sql) {
  103. $db=self::cdb ();
  104. return $db->fetchAll($sql);
  105. }
  106. /**
  107. * Directly execute sql query
  108. * @param $sql Query sql statement
  109. * @return
  110. */
  111. public static function query($sql) {
  112. $db=self::cdb();
  113. return $db->exec($sql);
  114. }
  115. /**
  116. * Execute sql query
  117. * @param $table table name
  118. * @param $where query condition
  119. * String, please follow the format:
  120. * String [Example 1: " id=1 and time>$time " ]
  121. * String [Example 2: array('catid=:catid AND time>=:time ',array(':catid'=>10,':time'=>'2012-02-10')) ]
  122. * Array [Example: array('name'=>'lanmps','password'=>'123456')]
  123. * @param $fields Field values ​​to be queried [Example `name`, `gender` ,`birthday`]
  124. * @param $limit Return result range [Example: 10 or 10,10 is empty by default]
  125. * @param $order Sorting method [Default is sorted by the database default method]
  126. * @param $group Grouping method [Default is empty]
  127. * @return array Query result set array
  128. */
  129. public static function select($table,$where = '', $fields = '*', $limit = '', $order = '', $group = '') {
  130. $db=self::cdb();
  131. $db->setTableName($table);
  132. return $db->select($where , $fields , $limit, $order, $group);
  133. }
  134. /**
  135. * Get single record query
  136. * @param $table table name
  137. * @param array $where query conditional statement
  138. * String, please follow the format:
  139. * String [Example 2: array('catid=:catid AND time> ;=:time ',array(':catid'=>10,':time'=>'2012-02-10')) ]
  140. * Array [Example: array('name'=>' lanmps','password'=>'123456')]
  141. * @param string $fields Field values ​​to be queried [eg `name`,`gender`,`birthday`]
  142. * @param string $order Sorting method[ The default is to sort according to the database default method]
  143. * @param string $group grouping method [default is empty]
  144. * @return array/null data query result set, if it does not exist, return empty
  145. */
  146. public static function getOne($table,$where,$fields = '*', $order = '', $group = '') {
  147. $db=self::cdb();
  148. $db->setTableName($table);
  149. return $db->get_one($where , $fields,$order, $group);
  150. }
  151. /**
  152. * Query multiple pieces of data and paginate
  153. * @param $table table name
  154. * @param $where query conditions
  155. * String, please follow the format:
  156. * String [Example 1: " id=1 and time>$time " ]
  157. * String [Example 2: array('catid=:catid AND time>=:time ',array(':catid'=>10,':time'=>'2012-02-10' )) ]
  158. * Array [Example: array('name'=>'lanmps','password'=>'123456')]
  159. * @param $fields field*,id
  160. * @param $order sort id desc ,orderlist asc
  161. * @param $page page number 1
  162. * @param $pagesize number of items per page
  163. * @return array('data'=>data,'count'=>total number of records)
  164. */
  165. public static function listInfo($table,$where = '',$fields='*', $order = '', $page = 1, $pagesize = 20) {
  166. $db=self::cdb();
  167. $db->setTableName($table);
  168. $d=$db->listinfo($where,$fields, $order, $page, $pagesize);
  169. return array('data'=>$d,'count'=>self::$db->number);
  170. }
  171. /**First parameter value
  172. * @param $sql
  173. * @return mixed
  174. */
  175. public static function resultFirst($sql){
  176. $db=self::cdb();
  177. return $db->resultFirst($sql);
  178. }
  179. }
复制代码

调用方法:

DB::insert('test',array('name'=>'test'));


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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,

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.

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

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�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles