PHPPDO for MYSQL encapsulation

Source: Internet
Author: User
PHPPDO for MYSQL encapsulation

  1. /**
  2. * Auther soulence
  3. * Call a data 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: Signature => PDO: FETCH_ASSOC );
  34. If ($ persistent === true ){
  35. $ Options_arr [PDO: ATTR_PERSISTENT] = true;
  36. }
  37. Try {
  38. $ Pdo = new PDO ($ mysql_server [$ flag] ['ononstring'], $ mysql_server [$ flag] ['username'], $ mysql_server [$ flag] ['password'], $ options_arr );
  39. } Catch (PDOException $ e ){
  40. Throw new Exception ($ e-> getMessage ());
  41. // Exit ('connection failed: '. $ 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 $ Who is the database corresponding to dbname?
  53. * @ Param bool $ whether the attr is a persistent connection
  54. * Return false indicates that the specified 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 operations
  72. * @ Param string $ SQL statement used to execute the query
  73. * @ Param array $ the condition format of data query is [': ID' => $ id,': name' => $ name] (recommended) or [1 => $ id, 2 => $ name]
  74. * @ Param bool $ one: whether to return a message. the default value 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. * Shared 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 operations for multiple SQL statements
  97. * @ Param array $ arr_ SQL the array format of the SQL statement for query execution is [$ sql1, $ sql2]
  98. * @ Param array $ arr_data the condition format corresponding to $ 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; default value: No. if it is set to true, only one data record is returned for each SQL statement.
  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 the number of pages
  122. * @ Param int $ pageSize indicates the number of entries per page.
  123. * @ Param array $ conditions for data query
  124. */
  125. Public function limitQuery ($ SQL, $ page = 0, $ pageSize = 20, $ data = [])
  126. {
  127. $ Page = intval ($ page );
  128. If ($ page <0 ){
  129. Return [];
  130. }
  131. $ PageSize = intval ($ pageSize );
  132. If ($ pageSize> 0) {// if pageSize is 0, all data is retrieved.
  133. $ SQL. = 'limit'. $ pageSize;
  134. If ($ page> 0 ){
  135. $ Start_limit = ($ page-1) * $ pageSize;
  136. $ SQL. = 'Offset'. $ start_limit;
  137. }
  138. }
  139. Return $ this-> query ($ SQL, $ data );
  140. }
  141. /**
  142. * This operation is used to add, delete, modify, and use transaction operations.
  143. * @ Param string $ SQL statement used to execute the query
  144. * @ Param array $ the condition format of data query is [': ID' => $ id,': name' => $ name] (recommended) or [1 => $ id, 2 => $ name]
  145. * @ Param bool $ whether the Transaction operation defaults to no
  146. */
  147. Public function executeDDL ($ SQL, $ data = [], $ Transaction = false ){
  148. If (! Is_array ($ data) |! Is_string ($ SQL ))
  149. Return false;
  150. $ This-> free ();
  151. If ($ Transaction)
  152. $ This-> pdo-> beginTransaction (); // start the transaction
  153. Try {
  154. $ This-> execRes ($ data, $ SQL );
  155. If ($ Transaction)
  156. $ This-> pdo-> commit (); // transaction commit
  157. Return $ this-> lastInsID;
  158. } Catch (Exception $ e ){
  159. If ($ Transaction)
  160. $ This-> pdo-> rollBack (); // transaction rollBack
  161. Throw new Exception ('error DDLExecute <===> '. $ e-> getMessage ());
  162. Return false;
  163. }
  164. }
  165. /**
  166. * This operation is used to add, delete, modify, and use transaction operations.
  167. * It executes multiple entries.
  168. * @ Param array $ array of SQL statements to be operated by arr_ SQL
  169. * @ Param array $ conditions of the SQL statement corresponding to the array and arr_data
  170. * @ Param bool $ whether the Transaction operation defaults to no
  171. */
  172. Public function executeDDLes ($ arr_ SQL, $ arr_data = [], $ Transaction = false ){
  173. If (! Is_array ($ arr_ SQL) | empty ($ arr_ SQL) |! Is_array ($ arr_data ))
  174. Return false;
  175. $ Res = [];
  176. $ This-> free ();
  177. If ($ Transaction)
  178. $ This-> pdo-> beginTransaction (); // start the transaction
  179. Try {
  180. $ I = 0;
  181. Foreach ($ arr_ SQL as $ val ){
  182. If (! Isset ($ arr_data [$ I])
  183. $ Arr_data [$ I] = [];
  184. Elseif (! Is_array ($ arr_data [$ I]) {
  185. If ($ Transaction)
  186. $ This-> pdo-> rollBack (); // transaction rollBack
  187. Throw new Exception ('error where DDLExecutees SQL: '. $ val. 'where:'. $ arr_data [$ I]);
  188. }
  189. $ This-> execRes ($ arr_data [$ I], $ val );
  190. $ Res [] = $ this-> lastInsID;
  191. $ I ++;
  192. }
  193. If ($ Transaction)
  194. $ This-> pdo-> commit (); // transaction commit
  195. Return $ res;
  196. } Catch (Exception $ e ){
  197. If ($ Transaction)
  198. $ This-> pdo-> rollBack (); // transaction rollBack
  199. Throw new Exception ('error DDLExecutees array_ SQL: '. json_encode ($ arr_ SQL).' <===> '. $ e-> getMessage ());
  200. Return false;
  201. }
  202. Return $ res;
  203. }
  204. /**
  205. * This method is used to calculate the number of items returned by the query. Note that it only supports the select count (*) from table... or select count (0) from table... method.
  206. * @ Param string $ SQL query SQL statement
  207. * @ Param array $ conditions of data SQL statements
  208. */
  209. Public function countRows ($ SQL, $ data = []) {
  210. If (! Is_array ($ data) | empty ($ SQL) |! Is_string ($ SQL ))
  211. Return false;
  212. $ This-> free ();
  213. $ Res = $ this-> pdoExec ($ data, $ SQL );
  214. If ($ res = false)
  215. Return false;
  216. Return $ this-> statement-> fetchColumn ();
  217. }
  218. /**
  219. * This method is used to calculate the number of items returned by a query. it executes multiple SQL statements.
  220. * @ Param string $ SQL query SQL statement
  221. * @ Param array $ conditions of data SQL statements
  222. */
  223. Public function countRowses ($ arr_ SQL, $ arr_data = []) {
  224. If (! Is_array ($ arr_ SQL) | empty ($ arr_ SQL) |! Is_array ($ arr_data ))
  225. Return false;
  226. $ Res = [];
  227. $ This-> free ();
  228. $ I = 0;
  229. Foreach ($ arr_ SQL as $ val ){
  230. If (! Isset ($ arr_data [$ I])
  231. $ Arr_data [$ I] = [];
  232. Elseif (! Is_array ($ arr_data [$ I])
  233. Throw new Exception ('error where CountRowses SQL: '. $ val. 'where:'. $ arr_data [$ I]);
  234. $ Res1 = $ this-> pdoExec ($ arr_data [$ I], $ val );
  235. If ($ res1 = false)
  236. $ Res [] = false;
  237. Else
  238. $ Res [] = $ this-> statement-> fetchColumn ();
  239. }
  240. Return $ res;
  241. }
  242. /**
  243. * Here we provide another method. because there are many projects that need to be provided to start transactions and then perform the final commit operation.
  244. * @ Param bool $ whether the Transaction operation defaults to no
  245. */
  246. Public function getDB ($ Transaction = false)
  247. {
  248. $ This-> Transaction = $ Transaction;
  249. $ This-> getConnect ();
  250. If ($ Transaction = true)
  251. $ This-> pdo-> beginTransaction (); // start the transaction
  252. Return $ this;
  253. }
  254. /**
  255. * This method can be executed multiple times. it executes DDL statements.
  256. * Note that it must be used together with getDB and sQCommit and cannot be used separately.
  257. * If the transaction sQCommit method is not enabled, you can not call it.
  258. * @ Param string $ SQL query SQL statement
  259. * @ Param array $ conditions of data SQL statements
  260. */
  261. Public function execSq ($ SQL, $ data = [])
  262. {
  263. If ($ this-> checkParams ($ SQL, $ data) === false)
  264. Return false;
  265. Try {
  266. $ This-> execRes ($ data, $ SQL );
  267. Return $ this-> lastInsID;
  268. } Catch (Exception $ e ){
  269. If (isset ($ this-> Transaction) & $ this-> Transaction = true)
  270. $ This-> pdo-> rollBack (); // transaction rollBack
  271. Throw new Exception ('error execSq <===> '. $ e-> getMessage ());
  272. Return false;
  273. } Finally {
  274. If (! Empty ($ this-> statement ))
  275. {
  276. $ This-> statement-> closeCursor ();
  277. Unset ($ this-> statement );
  278. }
  279. }
  280. }
  281. /**
  282. * To execute the query method, you need to upload a database connection object.
  283. * @ Param string $ SQL statement used to execute the query
  284. * @ Param array $ the condition format of data query is [': ID' => $ id,': name' => $ name] (recommended) or [1 => $ id, 2 => $ name]
  285. * @ Param bool $ one: whether to return a message. the default value is No.
  286. */
  287. Public function querySq ($ SQL, $ data = [], $ one = false)
  288. {
  289. If ($ this-> checkParams ($ SQL, $ data) === false)
  290. Return false;
  291. Return $ this-> pdoExecSq ($ SQL, $ data, [1, $ one]);
  292. }
  293. /**
  294. * Paging encapsulation
  295. *
  296. * @ Param string $ SQL
  297. * @ Param int $ page indicates the number of pages
  298. * @ Param int $ pageSize indicates the number of entries per page.
  299. * @ Param array $ conditions for data query
  300. */
  301. Public function limitQuerySq ($ SQL, $ page = 0, $ pageSize = 20, $ data = [])
  302. {
  303. $ Page = intval ($ page );
  304. If ($ page <0 ){
  305. Return [];
  306. }
  307. $ PageSize = intval ($ pageSize );
  308. If ($ pageSize> 0) {// if pageSize is 0, all data is retrieved.
  309. $ SQL. = 'limit'. $ pageSize;
  310. If ($ page> 0 ){
  311. $ Start_limit = ($ page-1) * $ pageSize;
  312. $ SQL. = 'Offset'. $ start_limit;
  313. }
  314. }
  315. Return $ this-> querySq ($ SQL, $ data );
  316. }
  317. /**
  318. * This method is used to calculate the number of items returned by the query. Note that it only supports the select count (*) from table... or select count (0) from table... method.
  319. * @ Param string $ SQL query SQL statement
  320. * @ Param array $ conditions of data SQL statements
  321. */
  322. Public function countRowsSq ($ SQL, $ data = []) {
  323. If ($ this-> checkParams ($ SQL, $ data) === false)
  324. Return false;
  325. Return $ this-> pdoExecSq ($ SQL, $ data, [2]);
  326. }
  327. /**
  328. * Here we provide another method. this is the final commit operation. if the transaction is not enabled, this method can not be called at the end.
  329. */
  330. Public function sQCommit ()
  331. {
  332. If (empty ($ this-> pdo) |! Is_object ($ this-> pdo ))
  333. Return false;
  334. If (isset ($ this-> Transaction) & $ this-> Transaction = true)
  335. $ This-> pdo-> commit (); // submit the transaction
  336. Unset ($ this-> pdo );
  337. }
  338. /**
  339. * Internal call method
  340. */
  341. Public function checkParams ($ SQL, $ data)
  342. {
  343. If (empty ($ this-> pdo) |! Is_object ($ this-> pdo) |! Is_array ($ data) | empty ($ SQL) |! Is_string ($ SQL ))
  344. Return false;
  345. Return true;
  346. }
  347. /**
  348. * Internal call method
  349. */
  350. Private function pdoExecSq ($ SQL, $ data, $ select = []) {
  351. Try {
  352. $ Res = $ this-> pdoExec ($ data, $ SQL );
  353. If (empty ($ select ))
  354. Return $ res;
  355. Else {
  356. If ($ select [0] === 1 ){
  357. If ($ select [1] === true)
  358. Return $ this-> statement-> fetch (PDO: FETCH_ASSOC );
  359. Else
  360. Return $ this-> statement-> fetchAll (PDO: FETCH_ASSOC );
  361. } Elseif ($ select [0] === 2)
  362. Return $ this-> statement-> fetchColumn ();
  363. Else
  364. Return false;
  365. }
  366. } Catch (Exception $ e ){
  367. Throw new Exception ($ e-> getMessage ());
  368. Return false;
  369. } Finally {
  370. If (! Empty ($ this-> statement ))
  371. {
  372. $ This-> statement-> closeCursor ();
  373. Unset ($ this-> statement );
  374. }
  375. }
  376. }
  377. /**
  378. * Internal call method
  379. */
  380. Private function execRes ($ data, $ SQL ){
  381. $ Res = $ this-> pdoExec ($ data, $ SQL );
  382. $ In_id = $ this-> pdo-> lastInsertId ();
  383. If (preg_match ("/^ \ s * (INSERT \ s + INTO | REPLACE \ s + INTO) \ s +/I", $ SQL )&&! Empty ($ in_id ))
  384. $ This-> lastInsID = $ in_id;
  385. Else
  386. $ This-> lastInsID = $ res;
  387. }
  388. /**
  389. * The internal call method is used to directly execute SQL statements.
  390. */
  391. Private function pdoExec ($ data, $ SQL ){
  392. $ This-> statement = $ this-> pdo-> prepare ($ SQL );
  393. If (false ===$ this-> statement)
  394. Return false;
  395. If (! Empty ($ data ))
  396. {
  397. Foreach ($ data as $ k => $ v)
  398. {
  399. $ This-> statement-> bindValue ($ k, $ v );
  400. }
  401. }
  402. $ Res = $ this-> statement-> execute ();
  403. If (! $ Res)
  404. {
  405. Throw new Exception ('SQL :'. $ SQL. '<=> where :'. json_encode ($ data ). '<===> error :'. json_encode ($ this-> statement-> errorInfo ()));
  406. } Else {
  407. Return $ res;
  408. }
  409. }
  410. /**
  411. * Internal call methods are used to release
  412. */
  413. Private function free ()
  414. {
  415. If (is_null ($ this-> pdo ))
  416. $ This-> getConnect ();
  417. If (! Empty ($ this-> statement ))
  418. {
  419. $ This-> statement-> closeCursor ();
  420. $ This-> statement = null;
  421. }
  422. }
  423. }
  424. ?>


PHP, PDO, MYSQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.