PHP PDO operation MySQL Package class

Source: Internet
Author: User
  1. /**
  2. * Auther 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 (' 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 Operational database objects
  52. * @param string $dbname The corresponding database is who
  53. * @param bool $attr is long connected
  54. * Return FALSE to indicate that a 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::d b ($this->dbname, $this->persistent);
  69. }
  70. /**
  71. * Query operation
  72. * @param string $sql SQL statement that executes the query
  73. * @param array $data The conditional format for the query is [': id ' = ' + $id, ': Name ' = ' $name] (recommended) or for [1=> $id,2=> $name]
  74. * @param bool $one whether to return a content default to 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 method of internal query
  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 SQL statement that executes the query is formatted as [$sql 1, $sql 2]
  98. * @param array $arr _data query with $arr_sql corresponding conditional format for [[': id ' = ' = $id, ': name ' = ' = ' $name],[': id ' + $id, ': Name ' = ' $name]] ( Recommended) or for [[1=> $id,2=> $name],[1=> $id,2=> $name]]
  99. * @param bool $one whether to return a content default to no here if set to True then each SQL returns only 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 Package
  119. *
  120. * @param string $sql
  121. * @param int $page Indicates the start of the first page
  122. * @param int $pageSize Indicates how many pages per page
  123. * @param the criteria for the array $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) {//PageSize is 0, all data is taken
  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 is used to add a delete modify operation using a transactional operation
  143. * @param string $sql SQL statement that executes the query
  144. * @param array $data The conditional format for the query is [': id ' = ' + $id, ': Name ' = ' $name] (recommended) or for [1=> $id,2=> $name]
  145. * @param bool $Transaction 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 ();//Open 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 is used to add a delete modify operation using a transactional operation
  167. * It's a multi-line execution.
  168. * @param array $arr _sql SQL statement that needs to be executed
  169. * @param array $arr _data The conditions of the SQL statement corresponding to the array
  170. * @param bool $Transaction 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 ();//Open 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 bars returned by the query note that it only supports select COUNT (*) from TABLE ... or select COUNT (0) from TABLE ... Way
  206. * SQL statement @param string $sql query
  207. * @param array $data The conditions of the SQL statement
  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 bars returned by the query it is to execute multiple SQL
  220. * SQL statement @param string $sql query
  221. * @param array $data The conditions of the SQL statement
  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. $res 1 = $this->pdoexec ($arr _data[$i], $val);
  235. if ($res 1 = = False)
  236. $res [] = false;
  237. Else
  238. $res [] = $this->statement->fetchcolumn ();
  239. }
  240. return $res;
  241. }
  242. /**
  243. * Here is another method because there will be a lot of things in the project that need to be opened and then the final commit
  244. * @param bool $Transaction 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 ();//Open transaction
  252. return $this;
  253. }
  254. /**
  255. * This method can be executed more than once it is executed by the DDL statement
  256. * Note that it is necessary to use together with GETDB and sqcommit can not be used alone OH
  257. * If the transaction is not turned on Sqcommit method can not call
  258. * SQL statement @param string $sql query
  259. * @param array $data The conditions of the SQL statement
  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. * Method of executing the query it needs to pass a connection database object
  283. * @param string $sql SQL statement that executes the query
  284. * @param array $data The conditional format for the query is [': id ' = ' + $id, ': Name ' = ' $name] (recommended) or for [1=> $id,2=> $name]
  285. * @param bool $one whether to return a content default to 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 Package
  295. *
  296. * @param string $sql
  297. * @param int $page Indicates the start of the first page
  298. * @param int $pageSize Indicates how many pages per page
  299. * @param the criteria for the array $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) {//PageSize is 0, all data is taken
  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 bars returned by the query note that it only supports select COUNT (*) from TABLE ... or select COUNT (0) from TABLE ... Way
  319. * SQL statement @param string $sql query
  320. * @param array $data The conditions of the SQL statement
  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's a way to provide this is the last commit operation if the transaction is not turned on this method can not be called at the end of the
  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 ();//Commit a 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. * methods used by the internal call method to execute SQL statements directly
  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. * The internal call method is used to release the
  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. ?>
Copy Code
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.