Home > Backend Development > PHP Tutorial > PHP PDO operation MYSQL encapsulation class

PHP PDO operation MYSQL encapsulation class

WBOY
Release: 2016-07-25 08:42:28
Original
1099 people have browsed it
  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 < 0) {
  129. return [];
  130. }
  131. $pageSize = intval($pageSize);
  132. if ($pageSize > 0) { // pageSize 为0时表示取所有数据
  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 for adding, deleting and modifying operations using transaction operations
  143. * @param string $sql The sql statement to execute the query
  144. * @param array $data The conditional format of the query is [':id'=>$id,' :name'=>$name] (recommended) or [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();//开启事务
  153. try{
  154. $this->execRes($data,$sql);
  155. if($Transaction)
  156. $this->pdo->commit();//事务提交
  157. return $this->lastInsID;
  158. } catch (Exception $e) {
  159. if($Transaction)
  160. $this->pdo->rollBack();//事务回滚
  161. throw new Exception('Error DDLExecute <=====>'.$e->getMessage());
  162. return false;
  163. }
  164. }
  165. /**
  166. * This is used to perform add, delete and modify operations using transaction operations
  167. * It executes multiple items
  168. * @param array $arr_sql The array of SQL statements that need 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();//开启事务
  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();//事务回滚
  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();//事务提交
  195. return $res;
  196. } catch (Exception $e) {
  197. if($Transaction)
  198. $this->pdo->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 SELECT COUNT(*) FROM TABLE... or SELECT COUNT(0) FROM TABLE...
  206. * @param string $sql The sql statement of the query
  207. * @param array $data Condition of 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 items returned by the query. It is used to execute multiple SQL statements.
  220. * @param string $sql The sql statement of the 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. $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 is another method because there will be many needs in the project to open transactions and then perform operations and finally submit
  244. * @param bool $Transaction Whether to perform transaction operations, the default is no
  245. */
  246. public function getDB($Transaction=false)
  247. {
  248. $this->Transaction = $Transaction;
  249. $this->getConnect();
  250. if($Transaction === true)
  251. $this->pdo->beginTransaction();//开启事务
  252. return $this;
  253. }
  254. /**
  255. * This method can be executed multiple times. It is used to execute DDL statements.
  256. * Note that it needs to be used together with getDB and sQCommit and cannot be used alone.
  257. * If the transaction is not enabled, the sQCommit method does not need to be called.
  258. * @param string $sql query sql statement
  259. * @param array $data Conditions of 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();//事务回滚
  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. * The method of executing the query requires passing a connection database object
  283. * @param string $sql The sql statement to execute the query
  284. * @param array $data The conditional format of the query is [':id'=>$id,': name'=>$name] (recommended) or [1=>$id,2=>$name]
  285. * @param bool $one Whether to return a piece of content, the default 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 which page to start from
  298. * @param int $pageSize indicates how many items per page
  299. * @param array $data query conditions
  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 为0时表示取所有数据
  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 SELECT COUNT(*) FROM TABLE... or SELECT COUNT(0) FROM TABLE...
  319. * @param string $sql The sql statement of the query
  320. * @param array $data Condition of 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 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
  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();//提交事务
  336. unset($this->pdo);
  337. }
  338. /**
  339. * Internal calling 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 calling 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 calling 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*(INSERTs+INTO|REPLACEs+INTO)s+/i", $sql) && !empty($in_id))
  384. $this->lastInsID = $in_id;
  385. else
  386. $this->lastInsID = $res;
  387. }
  388. /**
  389. * Internal calling method 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 calling method 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


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template