search
HomeBackend DevelopmentPHP TutorialPHP PDO operation MYSQL encapsulation class

  1. /**
  2. * author soulence
  3. * Call data class file
  4. * modify 2015/06/12
  5. */
  6. class DBConnect
  7. {
  8. private $dbname = null;
  9. private $pdo = null;
  10. private $persistent = false;
  11. private $statement = null;
  12. private $lastInsID = null;
  13. private static $_instance = [];
  14. private function __construct($dbname,$attr)
  15. {
  16. $this->dbname = $dbname;
  17. $this->persistent = $attr;
  18. }
  19. public static function db($flag='r',$persistent=false)
  20. {
  21. if(!isset($flag)){
  22. $flag = 'r';
  23. }
  24. if (!class_exists('PDO'))
  25. {
  26. throw new Exception('not found 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 => 'SET NAMES '.$mysql_server[$flag]['charset'],PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC);
  34. if($persistent === true){
  35. $options_arr[PDO::ATTR_PERSISTENT] = true;
  36. }
  37. try {
  38. $pdo = new PDO($mysql_server[$flag]['connectionString'],$mysql_server[$flag]['username'],$mysql_server[$flag]['password'],$options_arr);
  39. } catch (PDOException $e) {
  40. throw new Exception($e->getMessage());
  41. //exit('连接失败:'.$e->getMessage());
  42. return false;
  43. }
  44. if(!$pdo) {
  45. throw new Exception('PDO CONNECT ERROR');
  46. return false;
  47. }
  48. return $pdo;
  49. }
  50. /**
  51. * Get the operation database object
  52. * @param string $dbname Who is the corresponding database?
  53. * @param bool $attr Whether the connection is long
  54. * Return false indicates that the given database does not exist
  55. */
  56. public static function getInstance($dbname = 'r',$attr = false)
  57. {
  58. $mysql_server = Yaf_Registry::get('mysql');
  59. if(!isset($mysql_server[$dbname])){
  60. return false;
  61. }
  62. $key = md5(md5($dbname.$attr,true));
  63. if (!isset(self::$_instance[$key]) || !is_object(self::$_instance[$key]))
  64. self::$_instance[$key] = new self($dbname,$attr);
  65. return self::$_instance[$key];
  66. }
  67. private function getConnect(){
  68. $this->pdo = self::db($this->dbname,$this->persistent);
  69. }
  70. /**
  71. * Query operation
  72. * @param string $sql SQL statement to execute the query
  73. * @param array $data The conditional format of the query is [':id'=>$id,':name'=>$name]( Recommended) or [1=>$id,2=>$name]
  74. * @param bool $one Whether to return a piece of content, the default is no
  75. */
  76. public function query($sql, $data = [], $one = false)
  77. {
  78. if (!is_array($data) || empty($sql) || !is_string($sql))
  79. return false;
  80. $this->free();
  81. return $this->queryCommon($data,$sql,$one);
  82. }
  83. /**
  84. * Common methods for internal queries
  85. */
  86. private function queryCommon($data,$sql,$one)
  87. {
  88. $this->pdoExec($data,$sql);
  89. if ($one){
  90. return $this->statement->fetch(PDO::FETCH_ASSOC);
  91. }else{
  92. return $this->statement->fetchAll(PDO::FETCH_ASSOC);
  93. }
  94. }
  95. /**
  96. * Query operation of multiple SQL statements
  97. * @param array $arr_sql The sql statement array format for executing the query is [$sql1,$sql2]
  98. * @param array $arr_data The conditional format corresponding to the query $arr_sql is [[' :id'=>$id,':name'=>$name],[':id'=>$id,':name'=>$name]] (recommended) or [[1 =>$id,2=>$name],[1=>$id,2=>$name]]
  99. * @param bool $one Whether to return a piece of content. The default is no. If set to true, then Each sql only returns one piece of data
  100. */
  101. public function queryes($arr_sql, $arr_data = [], $one = false)
  102. {
  103. if(!is_array($arr_sql) || empty($arr_sql) || !is_array($arr_data))
  104. return false;
  105. $this->free();
  106. $res = [];$i = 0;
  107. foreach ($arr_sql as $val) {
  108. if(!isset($arr_data[$i]))
  109. $arr_data[$i] = [];
  110. elseif(!is_array($arr_data[$i]))
  111. throw new Exception('Error where queryes sql:'.$val.' where:'.$arr_data[$i]);
  112. $res[] = $this->queryCommon($arr_data[$i],$val,$one);
  113. $i++;
  114. }
  115. return $res;
  116. }
  117. /**
  118. * Paging encapsulation
  119. *
  120. * @param string $sql
  121. * @param int $page indicates which page to start from
  122. * @param int $pageSize indicates how many items per page
  123. * @param array $data query conditions
  124. */
  125. public function limitQuery($sql, $page=0, $pageSize=20, $data = [])
  126. {
  127. $page = intval($page);
  128. if ($page return [];
  129. }
  130. $pageSize = intval($pageSize);
  131. if ($pageSize > 0) { // pageSize 为0时表示取所有数据
  132. $sql .= ' LIMIT ' . $pageSize;
  133. if ($page > 0) {
  134. $start_limit = ($page - 1) * $pageSize;
  135. $sql .= ' OFFSET ' . $start_limit;
  136. }
  137. }
  138. return $this->query($sql, $data);
  139. }
  140. /**
  141. * This is used for adding, deleting and modifying operations using transaction operations
  142. * @param string $sql The sql statement to execute the query
  143. * @param array $data The conditional format of the query is [':id'=>$id,' :name'=>$name] (recommended) or [1=>$id,2=>$name]
  144. * @param bool $Transaction Whether the transaction operation defaults to No
  145. */
  146. public function executeDDL($sql, $data = [],$Transaction = false){
  147. if (!is_array($data) || !is_string($sql))
  148. return false;
  149. $this->free();
  150. if($Transaction)
  151. $this->pdo->beginTransaction();//开启事务
  152. try{
  153. $this->execRes($data,$sql);
  154. if($Transaction)
  155. $this->pdo->commit();//事务提交
  156. return $this->lastInsID;
  157. } catch (Exception $e) {
  158. if($Transaction)
  159. $this->pdo->rollBack();//事务回滚
  160. throw new Exception('Error DDLExecute '.$e->getMessage());
  161. return false;
  162. }
  163. }
  164. /**
  165. * This is used to perform add, delete and modify operations using transaction operations
  166. * It executes multiple items
  167. * @param array $arr_sql The array of SQL statements that need to be executed
  168. * @param array $arr_data The conditions of the SQL statement corresponding to the array
  169. * @param bool $Transaction Whether the transaction operation defaults to No
  170. */
  171. public function executeDDLes($arr_sql, $arr_data = [],$Transaction = false){
  172. if(!is_array($arr_sql) || empty($arr_sql) || !is_array($arr_data))
  173. return false;
  174. $res = [];
  175. $this->free();
  176. if($Transaction)
  177. $this->pdo->beginTransaction();//开启事务
  178. try{
  179. $i = 0;
  180. foreach($arr_sql as $val){
  181. if(!isset($arr_data[$i]))
  182. $arr_data[$i] = [];
  183. elseif(!is_array($arr_data[$i])){
  184. if($Transaction)
  185. $this->pdo->rollBack();//事务回滚
  186. throw new Exception('Error where DDLExecutees sql:'.$val.' where:'.$arr_data[$i]);
  187. }
  188. $this->execRes($arr_data[$i],$val);
  189. $res[] = $this->lastInsID;
  190. $i++;
  191. }
  192. if($Transaction)
  193. $this->pdo->commit();//事务提交
  194. return $res;
  195. } catch (Exception $e) {
  196. if($Transaction)
  197. $this->pdo->rollBack();//事务回滚
  198. throw new Exception('Error DDLExecutees array_sql:'.json_encode($arr_sql).' '.$e->getMessage());
  199. return false;
  200. }
  201. return $res;
  202. }
  203. /**
  204. * This method is used to calculate the number of items returned by the query. Note that it only supports SELECT COUNT(*) FROM TABLE... or SELECT COUNT(0) FROM TABLE...
  205. * @param string $sql The sql statement of the query
  206. * @param array $data Condition of SQL statement
  207. */
  208. public function countRows($sql,$data = []){
  209. if (!is_array($data) || empty($sql) || !is_string($sql))
  210. return false;
  211. $this->free();
  212. $res = $this->pdoExec($data,$sql);
  213. if($res == false)
  214. return false;
  215. return $this->statement->fetchColumn();
  216. }
  217. /**
  218. * This method is used to calculate the number of items returned by the query. It is used to execute multiple SQL statements.
  219. * @param string $sql The sql statement of the query
  220. * @param array $data The conditions of the SQL statement
  221. */
  222. public function countRowses($arr_sql,$arr_data = []){
  223. if(!is_array($arr_sql) || empty($arr_sql) || !is_array($arr_data))
  224. return false;
  225. $res = [];
  226. $this->free();
  227. $i = 0;
  228. foreach ($arr_sql as $val) {
  229. if(!isset($arr_data[$i]))
  230. $arr_data[$i] = [];
  231. elseif(!is_array($arr_data[$i]))
  232. throw new Exception('Error where CountRowses sql:'.$val.' where:'.$arr_data[$i]);
  233. $res1 = $this->pdoExec($arr_data[$i],$val);
  234. if($res1 == false)
  235. $res[] = false;
  236. else
  237. $res[] = $this->statement->fetchColumn();
  238. }
  239. return $res;
  240. }
  241. /**
  242. * Here is another method because there will be many needs in the project to open transactions and then perform operations and finally submit
  243. * @param bool $Transaction Whether to perform transaction operations, the default is no
  244. */
  245. public function getDB($Transaction=false)
  246. {
  247. $this->Transaction = $Transaction;
  248. $this->getConnect();
  249. if($Transaction === true)
  250. $this->pdo->beginTransaction();//开启事务
  251. return $this;
  252. }
  253. /**
  254. * This method can be executed multiple times. It is used to execute DDL statements.
  255. * Note that it needs to be used together with getDB and sQCommit and cannot be used alone.
  256. * If the transaction is not enabled, the sQCommit method does not need to be called.
  257. * @param string $sql query sql statement
  258. * @param array $data Conditions of SQL statement
  259. */
  260. public function execSq($sql,$data = [])
  261. {
  262. if($this->checkParams($sql,$data) === false)
  263. return false;
  264. try{
  265. $this->execRes($data,$sql);
  266. return $this->lastInsID;
  267. } catch (Exception $e) {
  268. if(isset($this->Transaction) && $this->Transaction === true)
  269. $this->pdo->rollBack();//事务回滚
  270. throw new Exception('Error execSq'.$e->getMessage());
  271. return false;
  272. } finally {
  273. if (!empty($this->statement))
  274. {
  275. $this->statement->closeCursor();
  276. unset($this->statement);
  277. }
  278. }
  279. }
  280. /**
  281. * The method of executing the query requires passing a connection database object
  282. * @param string $sql The sql statement to execute the query
  283. * @param array $data The conditional format of the query is [':id'=>$id,': name'=>$name] (recommended) or [1=>$id,2=>$name]
  284. * @param bool $one Whether to return a piece of content, the default is no
  285. */
  286. public function querySq($sql,$data = [],$one = false)
  287. {
  288. if($this->checkParams($sql,$data) === false)
  289. return false;
  290. return $this->pdoExecSq($sql,$data,[1,$one]);
  291. }
  292. /**
  293. * Paging encapsulation
  294. *
  295. * @param string $sql
  296. * @param int $page indicates which page to start from
  297. * @param int $pageSize indicates how many items per page
  298. * @param array $data query conditions
  299. */
  300. public function limitQuerySq($sql, $page=0, $pageSize=20, $data = [])
  301. {
  302. $page = intval($page);
  303. if ($page return [];
  304. }
  305. $pageSize = intval($pageSize);
  306. if ($pageSize > 0) { // pageSize 为0时表示取所有数据
  307. $sql .= ' LIMIT ' . $pageSize;
  308. if ($page > 0) {
  309. $start_limit = ($page - 1) * $pageSize;
  310. $sql .= ' OFFSET ' . $start_limit;
  311. }
  312. }
  313. return $this->querySq($sql, $data);
  314. }
  315. /**
  316. * This method is used to calculate the number of items returned by the query. Note that it only supports SELECT COUNT(*) FROM TABLE... or SELECT COUNT(0) FROM TABLE...
  317. * @param string $sql The sql statement of the query
  318. * @param array $data Condition of SQL statement
  319. */
  320. public function countRowsSq($sql,$data = []){
  321. if($this->checkParams($sql,$data) === false)
  322. return false;
  323. return $this->pdoExecSq($sql,$data,[2]);
  324. }
  325. /**
  326. * Here is another method. This is the final commit operation. If the transaction is not started, this method does not need to be called at the end
  327. */
  328. public function sQCommit()
  329. {
  330. if(empty($this->pdo) || !is_object($this->pdo))
  331. return false;
  332. if(isset($this->Transaction) && $this->Transaction === true)
  333. $this->pdo->commit();//提交事务
  334. unset($this->pdo);
  335. }
  336. /**
  337. * Internal calling method
  338. */
  339. public function checkParams($sql,$data)
  340. {
  341. if (empty($this->pdo) || !is_object($this->pdo) || !is_array($data) || empty($sql) || !is_string($sql))
  342. return false;
  343. return true;
  344. }
  345. /**
  346. * Internal calling method
  347. */
  348. private function pdoExecSq($sql,$data,$select = []){
  349. try{
  350. $res = $this->pdoExec($data,$sql);
  351. if(empty($select))
  352. return $res;
  353. else{
  354. if($select[0] === 1){
  355. if($select[1] === true)
  356. return $this->statement->fetch(PDO::FETCH_ASSOC);
  357. else
  358. return $this->statement->fetchAll(PDO::FETCH_ASSOC);
  359. }elseif($select[0] === 2)
  360. return $this->statement->fetchColumn();
  361. else
  362. return false;
  363. }
  364. } catch (Exception $e) {
  365. throw new Exception($e->getMessage());
  366. return false;
  367. } finally {
  368. if (!empty($this->statement))
  369. {
  370. $this->statement->closeCursor();
  371. unset($this->statement);
  372. }
  373. }
  374. }
  375. /**
  376. * Internal calling method
  377. */
  378. private function execRes($data,$sql){
  379. $res = $this->pdoExec($data,$sql);
  380. $in_id = $this->pdo->lastInsertId();
  381. if (preg_match("/^s*(INSERTs+INTO|REPLACEs+INTO)s+/i", $sql) && !empty($in_id))
  382. $this->lastInsID = $in_id;
  383. else
  384. $this->lastInsID = $res;
  385. }
  386. /**
  387. * Internal calling method used to directly execute SQL statements
  388. */
  389. private function pdoExec($data,$sql){
  390. $this->statement = $this->pdo->prepare($sql);
  391. if (false === $this->statement)
  392. return false;
  393. if (!empty($data))
  394. {
  395. foreach ($data as $k => $v)
  396. {
  397. $this->statement->bindValue($k, $v);
  398. }
  399. }
  400. $res = $this->statement->execute();
  401. if (!$res)
  402. {
  403. throw new Exception('sql:'.$sql.'where:'.json_encode($data).'error:'.json_encode($this->statement->errorInfo()));
  404. }else{
  405. return $res;
  406. }
  407. }
  408. /**
  409. * Internal calling method used to release
  410. */
  411. private function free()
  412. {
  413. if (is_null($this->pdo))
  414. $this->getConnect();
  415. if (!empty($this->statement))
  416. {
  417. $this->statement->closeCursor();
  418. $this->statement = null;
  419. }
  420. }
  421. }
  422. ?>
复制代码

PHP, PDO, MYSQL


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment