search
HomeBackend DevelopmentPHP TutorialPHP PDO encapsulated static class code sharing

  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
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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 Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor