Phppdo database operation encapsulation code

Source: Internet
Author: User
Tags pconnect
Phppdo database operation encapsulation code

  1. /**

  2. * Database PDO operations
  3. */
  4. Class MysqlPdo {
  5. Public static $ PDOStatement = null;
  6. /**
  7. * Database connection parameter configuration
  8. * @ Var array
  9. * @ Access public
  10. */
  11. Public static $ config = array ();
  12. /**
  13. * Whether to use permanent connection
  14. * @ Var bool
  15. * @ Access public
  16. */
  17. Public static $ pconnect = false;
  18. /**
  19. * Error message
  20. * @ Var string
  21. * @ Access public
  22. */
  23. Public static $ error = '';
  24. /**
  25. * In single-piece mode, the unique instance of the Pdo class is saved and the connection resource of the database is saved.
  26. * @ Var object
  27. * @ Access public
  28. */
  29. Protected static $ link;
  30. /**
  31. * Whether the database has been connected
  32. * @ Var bool
  33. * @ Access public
  34. */
  35. Public static $ connected = false;
  36. /**
  37. * Database version
  38. * @ Var string
  39. * @ Access public
  40. */
  41. Public static $ dbVersion = null;
  42. /**
  43. * Current SQL statement
  44. * @ Var string
  45. * @ Access public
  46. */
  47. Public static $ queryStr = '';
  48. /**
  49. * Last inserted record ID
  50. * @ Var integer
  51. * @ Access public
  52. */
  53. Public static $ lastInsertId = null;
  54. /**
  55. * Number of affected records returned
  56. * @ Var integer
  57. * @ Access public
  58. */
  59. Public static $ numRows = 0;
  60. // Transaction instruction count
  61. Public static $ transTimes = 0;
  62. /**
  63. * Constructor,
  64. * @ Param $ dbconfig database connection information, array ('servername', 'username', 'password', 'defaultdb', 'DB _ port', 'DB _ type ')
  65. */
  66. Public function _ construct ($ dbConfig = ''){
  67. If (! Class_exists ('pdo') self: throw_exception ("not supported: PDO ");
  68. // Use the default data definition if no parameters are transmitted
  69. If (! Is_array ($ dbConfig )){
  70. $ DbConfig = array (
  71. 'Hostname' => DB_HOST,
  72. 'Username' => DB_USER,
  73. 'Password' => DB_PWD,
  74. 'Database' => DB_NAME,
  75. 'Hostport' => DB_PORT,
  76. 'Dbms '=> DB_TYPE,
  77. 'Dsn '=> DB_TYPE. ": host =". DB_HOST. "; dbname =". DB_NAME
  78. );
  79. }
  80. If (empty ($ dbConfig ['hostname']) self: throw_exception ("no database configuration defined ");
  81. Self: $ config = $ dbConfig;
  82. If (empty (self: $ config ['params']) self: $ config ['params'] = array ();
  83. /************************************ Gorgeous separation line **************************************** ***/
  84. If (! Isset (self: $ link )){
  85. $ Configs = self: $ config;
  86. If (self: $ pconnect ){
  87. $ Configs ['params'] [constant ('pdo: ATTR_PERSISTENT ')] = true;
  88. }
  89. Try {
  90. Self: $ link = new PDO ($ configs ['dsn '], $ configs ['username'], $ configs ['password'], $ configs ['params']);
  91. } Catch (PDOException $ e ){
  92. Self: throw_exception ($ e-> getMessage ());
  93. }
  94. If (! Self: $ link ){
  95. Self: throw_exception ('pdo CONNECT error ');
  96. Return false;
  97. }
  98. Self: $ link-> exec ('set names'. DB_CHARSET );
  99. Self: $ dbVersion = self: $ link-> getAttribute (constant ("PDO: ATTR_SERVER_INFO "));
  100. // Mark the connection successful
  101. Self: $ connected = true;
  102. // Cancel database connection configuration
  103. Unset ($ configs );
  104. }
  105. Return self: $ link;
  106. }
  107. /**
  108. * Release query results
  109. * @ Access function
  110. */
  111. Static function free (){
  112. Self: $ PDOStatement = null;
  113. }
  114. /************************/
  115. /* Database operations */
  116. /************************/
  117. /**
  118. * Obtain all query data
  119. * @ Access function
  120. * @ Return array
  121. */
  122. Static function getAll ($ SQL = null ){
  123. If ($ SQL! = Null)
  124. {
  125. Self: query ($ SQL );
  126. }
  127. // Return the dataset
  128. $ Result = self ::$ PDOStatement-> fetchAll (constant ('pdo: FETCH_ASSOC '));
  129. Return $ result;
  130. }
  131. /**
  132. * Obtain a query result.
  133. * @ Access function
  134. * @ Param string $ SQL SQL command
  135. * @ Param integer $ seek pointer position
  136. * @ Return array
  137. */
  138. Static function getRow ($ SQL = null ){
  139. If ($ SQL! = Null)
  140. {
  141. Self: query ($ SQL );
  142. }
  143. // Returns the array set.
  144. $ Result = self ::$ PDOStatement-> fetch (constant ('pdo: FETCH_ASSOC '), constant ('pdo: FETCH_ORI_NEXT '));
  145. Return $ result;
  146. }
  147. /**
  148. * Execute SQL statements to automatically query or execute operations.
  149. * @ Access function
  150. * @ Param string $ SQL SQL command
  151. * @ Return mixed
  152. */
  153. Static function doSql ($ SQL = ''){
  154. If (self: isMainIps ($ SQL )){
  155. Return self: execute ($ SQL );
  156. } Else {
  157. Return self: getAll ($ SQL );
  158. }
  159. }
  160. /**
  161. * Query table records based on the specified ID (for single table operations only)
  162. * @ Access function
  163. * @ Param integer $ priId primary key ID
  164. * @ Param string $ tables data table name
  165. * @ Param string $ fields field name
  166. * @ Return ArrayObject table record
  167. */
  168. Static function findById ($ tabName, $ priId, $ fields = '*'){
  169. $ SQL = 'SELECT % s FROM % s WHERE id = % d ';
  170. Return self: getRow (sprintf ($ SQL, self: parseFields ($ fields), $ tabName, $ priId ));
  171. }
  172. /**
  173. * Query records
  174. * @ Access function
  175. * @ Param string $ tables data table name
  176. * @ Param mixed $ where query condition
  177. * @ Param string $ fields field name
  178. * @ Param string $ order sorting
  179. * @ Param string $ limit: how many data records are Retrieved?
  180. * @ Param string $ group
  181. * @ Param string $ having
  182. * @ Param boolean $ whether lock is locked
  183. * @ Return ArrayObject
  184. */
  185. Static function find ($ tables, $ where = "", $ fields = '*', $ order = null, $ limit = null, $ group = null, $ having = null) {
  186. $ SQL = 'select'. self: parseFields ($ fields)
  187. . 'From'. $ tables
  188. . Self: parseWhere ($ where)
  189. . Self: parseGroup ($ group)
  190. . Self: parseHaving ($ having)
  191. . Self: parseOrder ($ order)
  192. . Self: parseLimit ($ limit );
  193. $ DataAll = self: getAll ($ SQL );
  194. If (count ($ dataAll) = 1) {$ rlt = $ dataAll [0];} else {$ rlt = $ dataAll ;}
  195. Return $ rlt;
  196. }
  197. /**
  198. * Insert (single) records
  199. * @ Access function
  200. * @ Param mixed $ data
  201. * @ Param string $ table data table name
  202. * @ Return false | integer
  203. */
  204. Function add ($ data, $ table ){
  205. // Filter submitted data
  206. $ Data = self: filterPost ($ table, $ data );
  207. Foreach ($ data as $ key => $ val ){
  208. If (is_array ($ val) & strtolower ($ val [0]) = 'Exp '){
  209. $ Val = $ val [1]; // use the expression ???
  210. } Elseif (is_scalar ($ val )){
  211. $ Val = self: fieldFormat ($ val );
  212. } Else {
  213. // Remove the composite object
  214. Continue;
  215. }
  216. $ Data [$ key] = $ val;
  217. }
  218. $ Fields = array_keys ($ data );
  219. Array_walk ($ fields, array ($ this, 'addspecialchar '));
  220. $ FieldsStr = implode (',', $ fields );
  221. $ Values = array_values ($ data );
  222. $ ValuesStr = implode (',', $ values );
  223. $ SQL = 'insert'. $ table. '('. $ fieldsStr. ') VALUES ('. $ valuesStr .')';
  224. Return self: execute ($ SQL );
  225. }
  226. /**
  227. * Update records
  228. * @ Access function
  229. * @ Param mixed $ sets Data
  230. * @ Param string $ table data table name
  231. * @ Param string $ where update condition
  232. * @ Param string $ limit
  233. * @ Param string $ order
  234. * @ Return false | integer
  235. */
  236. Static function update ($ sets, $ table, $ where, $ limit = 0, $ order = ''){
  237. $ Sets = self: filterPost ($ table, $ sets );
  238. $ SQL = 'update '. $ table. 'set '. self: parseSets ($ sets ). self: parseWhere ($ where ). self: parseOrder ($ order ). self: parseLimit ($ limit );
  239. Return self: execute ($ SQL );
  240. }
  241. /**
  242. * Save the value of a field
  243. * @ Access function
  244. * @ Param string $ field name of the field to be saved
  245. * @ Param string $ value field value
  246. * @ Param string $ table data table
  247. * @ Param string $ where save condition
  248. * @ Param boolean $ asString whether the field value is a string
  249. * @ Return void
  250. */
  251. Static function setField ($ field, $ value, $ table, $ condition = "", $ asString = false ){
  252. // If '(' is regarded as an SQL command update; otherwise, the field content is updated as a pure string.
  253. If (false = strpos ($ value, '(') | $ asString) $ value = '"'. $ value .'"';
  254. $ SQL = 'update'. $ table. 'set'. $ field. '='. $ value. self: parseWhere ($ condition );
  255. Return self: execute ($ SQL );
  256. }
  257. /**
  258. * Delete a record
  259. * @ Access function
  260. * @ Param mixed $ where is the condition Map, Array, or String.
  261. * @ Param string $ table data table name
  262. * @ Param string $ limit
  263. * @ Param string $ order
  264. * @ Return false | integer
  265. */
  266. Static function remove ($ where, $ table, $ limit = '', $ order = ''){
  267. $ SQL = 'delete from'. $ table. self: parseWhere ($ where). self: parseOrder ($ order). self: parseLimit ($ limit );
  268. Return self: execute ($ SQL );
  269. }
  270. /**
  271. + ----------------------------------------------------------
  272. * Modify or save data (for single table operations only)
  273. * If there is a primary key ID, it is modified. if there is no primary key ID, it is added.
  274. * Modification record:
  275. + ----------------------------------------------------------
  276. * @ Access function
  277. + ----------------------------------------------------------
  278. * @ Param $ tabName table name
  279. * @ Param $ _ POST of the form submitted by aPost
  280. * @ Param $ priId primary key ID
  281. * @ Param $ aNot the field or array to be excluded
  282. * @ Param $ aCustom a custom array, which is appended to the database and saved
  283. * @ Param $ whether isExits already exists: true, not exist: false
  284. + ----------------------------------------------------------
  285. * @ Return Boolean whether modification or saving is successful
  286. + ----------------------------------------------------------
  287. */
  288. Function saveOrUpdate ($ tabName, $ aPost, $ priId = "", $ aNot = "", $ aCustom = "", $ isExits = false ){
  289. If (empty ($ tabName) |! Is_array ($ aPost) | is_int ($ aNot) return false;
  290. If (is_string ($ aNot )&&! Empty ($ aNot) $ aNot = array ($ aNot );
  291. If (is_array ($ aNot) & is_int (key ($ aNot) $ aPost = array_diff_key ($ aPost, array_flip ($ aNot ));
  292. If (is_array ($ aCustom) & is_string (key ($ aCustom) $ aPost = array_merge ($ aPost, $ aCustom );
  293. If (empty ($ priId )&&! $ IsExits) {// add
  294. $ APost = array_filter ($ aPost, array ($ this, 'removeempty '));
  295. Return self: add ($ aPost, $ tabName );
  296. } Else {// modify
  297. Return self: update ($ aPost, $ tabName, "id =". $ priId );
  298. }
  299. }
  300. /**
  301. * Obtain the SQL statement of the last query
  302. * @ Access function
  303. * @ Param
  304. * @ Return String the SQL statement executed
  305. */
  306. Static function getLastSql (){
  307. $ Link = self: $ link;
  308. If (! $ Link) return false;
  309. Return self: $ queryStr;
  310. }
  311. /**
  312. * Obtain the last inserted ID.
  313. * @ Access function
  314. * @ Param
  315. * @ Return the ID of the last inserted integer
  316. */
  317. Static function getLastInsId (){
  318. $ Link = self: $ link;
  319. If (! $ Link) return false;
  320. Return self: $ lastInsertId;
  321. }
  322. /**
  323. * Obtain the database version.
  324. * @ Access function
  325. * @ Param
  326. * @ Return string
  327. */
  328. Static function getDbVersion (){
  329. $ Link = self: $ link;
  330. If (! $ Link) return false;
  331. Return self: $ dbVersion;
  332. }
  333. /**
  334. * Obtain database table information
  335. * @ Access function
  336. * @ Return array
  337. */
  338. Static function getTables (){
  339. $ Info = array ();
  340. If (self: query ("show tables ")){
  341. $ Result = self: getAll ();
  342. Foreach ($ result as $ key => $ val ){
  343. $ Info [$ key] = current ($ val );
  344. }
  345. }
  346. Return $ info;
  347. }
  348. /**
  349. * Obtain the field information of the data table.
  350. * @ Access function
  351. * @ Return array
  352. */
  353. Static function getFields ($ tableName ){
  354. // Obtain the database connection
  355. $ Link = self: $ link;
  356. $ SQL = "SELECT
  357. ORDINAL_POSITION, COLUMN_NAME, COLUMN_TYPE, DATA_TYPE,
  358. IF (ISNULL (CHARACTER_MAXIMUM_LENGTH), (NUMERIC_PRECISION + NUMERIC_SCALE), CHARACTER_MAXIMUM_LENGTH) as maxchar,
  359. IS_NULLABLE, COLUMN_DEFAULT, COLUMN_KEY, EXTRA, COLUMN_COMMENT
  360. FROM
  361. INFORMATION_SCHEMA.COLUMNS
  362. WHERE
  363. TABLE_NAME =: tabName AND TABLE_SCHEMA = '". DB_NAME ."'";
  364. Self: $ queryStr = sprintf ($ SQL, $ tableName );
  365. $ Something = $ link-> prepare ($ SQL );
  366. $ Something-> bindParam (': tabname', $ tableName );
  367. $ Something-> execute ();
  368. $ Result = $ Something-> fetchAll (constant ('pdo: FETCH_ASSOC '));
  369. $ Info = array ();
  370. Foreach ($ result as $ key => $ val ){
  371. $ Info [$ val ['column _ name'] = array (
  372. 'Postion' => $ val ['ordinal _ position'],
  373. 'Name' => $ val ['column _ name'],
  374. 'Type' => $ val ['column _ type'],
  375. 'D _ type' => $ val ['data _ type'],
  376. 'Length' => $ val ['maxchar '],
  377. 'Notnull '=> (strtolower ($ val ['is _ nullable']) = "no "),
  378. 'Default' => $ val ['column _ default'],
  379. 'Primary' => (strtolower ($ val ['column _ key']) = 'pri '),
  380. 'Autoinc' => (strtolower ($ val ['Extra ']) = 'auto _ increment '),
  381. 'Comment' => $ val ['column _ comment']
  382. );
  383. }
  384. // If an error exists, an exception is thrown.
  385. Self: haveErrorThrowException ();
  386. Return $ info;
  387. }
  388. /**
  389. * Shut down the database.
  390. * @ Access function
  391. */
  392. Static function close (){
  393. Self: $ link = null;
  394. }
  395. /**
  396. * SQL Command Security filtering
  397. * @ Access function
  398. * @ Param string $ str SQL command
  399. * @ Return string
  400. */
  401. Static function escape_string ($ str ){
  402. Return addslashes ($ str );
  403. }
  404. /************************/
  405. /* Internal operation method */
  406. /************************/
  407. /**
  408. * An error occurs and an exception is thrown.
  409. * @ Access function
  410. * @ Return
  411. */
  412. Static function haveErrorThrowException (){
  413. $ Obj = empty (self: $ PDOStatement )? Self ::$ link: self ::$ PDOStatement;
  414. $ ArrError = $ obj-> errorInfo ();
  415. If ($ arrError [0]! = '000000') {// error message
  416. Self: $ error = $ arrError [0]. "|". $ arrError [2]."
    [SQL]: ". self: $ queryStr ."
    ";
  417. Self: throw_exception (self: $ error );
  418. Return false;
  419. }
  420. // Throws an exception mainly for the execute () method
  421. If (self ::$ queryStr = '') self: throw_exception ('query was empty

    [SQL statement]: ');
  422. }
  423. /**
  424. * Where analysis
  425. * @ Access function
  426. * @ Param mixed $ where query condition
  427. * @ Return string
  428. */
  429. Static function parseWhere ($ where ){
  430. $ WhereStr = '';
  431. If (is_string ($ where) | is_null ($ where )){
  432. $ WhereStr = $ where;
  433. }
  434. Return empty ($ whereStr )? '': 'Where'. $ whereStr;
  435. }
  436. /**
  437. * Order analysis
  438. * @ Access function
  439. * @ Param mixed $ order sorting
  440. * @ Return string
  441. */
  442. Static function parseOrder ($ order ){
  443. $ OrderStr = '';
  444. If (is_array ($ order ))
  445. $ OrderStr. = 'Order by'. implode (',', $ ORDER );
  446. Else if (is_string ($ order )&&! Empty ($ order ))
  447. $ OrderStr. = 'Order by'. $ ORDER;
  448. Return $ orderStr;
  449. }
  450. /**
  451. * Limit analysis
  452. * @ Access function
  453. * @ Param string $ limit
  454. * @ Return string
  455. */
  456. Static function parseLimit ($ limit ){
  457. $ LimitStr = '';
  458. If (is_array ($ limit )){
  459. If (count ($ limit)> 1)
  460. $ LimitStr. = 'limit'. $ LIMIT [0]. ','. $ limit [1]. '';
  461. Else
  462. $ LimitStr. = 'limit'. $ LIMIT [0]. '';
  463. } Else if (is_string ($ limit )&&! Empty ($ limit )){
  464. $ LimitStr. = 'limit'. $ LIMIT .'';
  465. }
  466. Return $ limitStr;
  467. }
  468. /**
  469. * Group Analysis
  470. * @ Access function
  471. * @ Param mixed $ group
  472. * @ Return string
  473. */
  474. Static function parseGroup ($ group ){
  475. $ GroupStr = '';
  476. If (is_array ($ group ))
  477. $ GroupStr. = 'group by'. implode (',', $ GROUP );
  478. Else if (is_string ($ group )&&! Empty ($ group ))
  479. $ GroupStr. = 'group by'. $ GROUP;
  480. Return empty ($ groupStr )? '': $ GroupStr;
  481. }
  482. /**
  483. * Having analysis
  484. * @ Access function
  485. * @ Param string $ having
  486. * @ Return string
  487. */
  488. Static function parseHaving ($ having ){
  489. $ HavingStr = '';
  490. If (is_string ($ having )&&! Empty ($ having ))
  491. $ HavingStr. = 'having '. $ HAVING;
  492. Return $ havingStr;
  493. }
  494. /**
  495. * Fields analysis
  496. * @ Access function
  497. * @ Param mixed $ fields
  498. * @ Return string
  499. */
  500. Function parseFields ($ fields ){
  501. If (is_array ($ fields )){
  502. Array_walk ($ fields, array ($ this, 'addspecialchar '));
  503. $ FieldsStr = implode (',', $ fields );
  504. } Else if (is_string ($ fields )&&! Empty ($ fields )){
  505. If (false === strpos ($ fields ,''')){
  506. $ Fields = explode (',', $ fields );
  507. Array_walk ($ fields, array ($ this, 'addspecialchar '));
  508. $ FieldsStr = implode (',', $ fields );
  509. } Else {
  510. $ FieldsStr = $ fields;
  511. }
  512. } Else $ fieldsStr = '*';
  513. Return $ fieldsStr;
  514. }
  515. /**
  516. * Sets analysis, called when updating data
  517. * @ Access function
  518. * @ Param mixed $ values
  519. * @ Return string
  520. */
  521. Private function parseSets ($ sets ){
  522. $ SetsStr = '';
  523. If (is_array ($ sets )){
  524. Foreach ($ sets as $ key => $ val ){
  525. $ Key = self: addSpecialChar ($ key );
  526. $ Val = self: fieldFormat ($ val );
  527. $ SetsStr. = "$ key =". $ val .",";
  528. }
  529. $ SetsStr = substr ($ setsStr, 0,-1 );
  530. } Else if (is_string ($ sets )){
  531. $ SetsStr = $ sets;
  532. }
  533. Return $ setsStr;
  534. }
  535. /**
  536. * Field formatting
  537. * @ Access function
  538. * @ Param mixed $ value
  539. * @ Return mixed
  540. */
  541. Static function fieldFormat (& $ value ){
  542. If (is_int ($ value )){
  543. $ Value = intval ($ value );
  544. } Else if (is_float ($ value )){
  545. $ Value = floatval ($ value );
  546. } Elseif (preg_match ('/^ \ (\ w * (\ + | \-| \ * | \/)? \ W * \) $/I ', $ value )){
  547. // Other fields can be directly used in the field values
  548. // For example, (score + 1) (name) must contain parentheses
  549. $ Value = $ value;
  550. } Else if (is_string ($ value )){
  551. $ Value = '\ ''. self: escape_string ($ value ).'\'';
  552. }
  553. Return $ value;
  554. }
  555. /**
  556. * The field and table name add' match
  557. * Ensure that the keyword used in the command is correct for mysql
  558. * @ Access function
  559. * @ Param mixed $ value
  560. * @ Return mixed
  561. */
  562. Static function addSpecialChar (& $ value ){
  563. If ('*' = $ value | false! = Strpos ($ value, '(') | false! = Strpos ($ value, '.') | false! = Strpos ($ value ,''')){
  564. // If it contains * or uses the SQL method, it is not processed.
  565. } Elseif (false === strpos ($ value ,''')){
  566. $ Value = '''. trim ($ value ).''';
  567. }
  568. Return $ value;
  569. }
  570. /**
  571. + ----------------------------------------------------------
  572. * Remove null elements
  573. + ----------------------------------------------------------
  574. * @ Access function
  575. + ----------------------------------------------------------
  576. * @ Param mixed $ value
  577. + ----------------------------------------------------------
  578. * @ Return mixed
  579. + ----------------------------------------------------------
  580. */
  581. Static function removeEmpty ($ value ){
  582. Return! Empty ($ value );
  583. }
  584. /**
  585. * Query execution mainly targets SELECT, SHOW, and other commands.
  586. * @ Access function
  587. * @ Param string $ SQL command
  588. * @ Return mixed
  589. */
  590. Static function query ($ SQL = ''){
  591. // Obtain the database connection
  592. $ Link = self: $ link;
  593. If (! $ Link) return false;
  594. Self: $ queryStr = $ SQL;
  595. // Release the previous query result
  596. If (! Empty (self ::$ PDOStatement) self: free ();
  597. Self: $ PDOStatement = $ link-> prepare (self ::$ queryStr );
  598. $ Bol = self: $ PDOStatement-> execute ();
  599. // If an error exists, an exception is thrown.
  600. Self: haveErrorThrowException ();
  601. Return $ bol;
  602. }
  603. /**
  604. * Database operation method
  605. * @ Access function
  606. * @ Param string $ SQL execution statement
  607. * @ Param boolean $ whether lock is locked (not locked by default)
  608. * @ Return void
  609. Public function execute ($ SQL = '', $ lock = false ){
  610. If (empty ($ SQL) $ SQL = $ this-> queryStr;
  611. Return $ this-> _ execute ($ SQL );
  612. }*/
  613. /**
  614. * Execute statements for INSERT, UPDATE, and DELETE
  615. * @ Access function
  616. * @ Param string $ SQL command
  617. * @ Return integer
  618. */
  619. Static function execute ($ SQL = ''){
  620. // Obtain the database connection
  621. $ Link = self: $ link;
  622. If (! $ Link) return false;
  623. Self: $ queryStr = $ SQL;
  624. // Release the previous query result
  625. If (! Empty (self ::$ PDOStatement) self: free ();
  626. $ Result = $ link-> exec (self: $ queryStr );
  627. // If an error exists, an exception is thrown.
  628. Self: haveErrorThrowException ();
  629. If (false ===$ result ){
  630. Return false;
  631. } Else {
  632. Self: $ numRows = $ result;
  633. Self: $ lastInsertId = $ link-> lastInsertId ();
  634. Return self: $ numRows;
  635. }
  636. }
  637. /**
  638. * Whether it is a database change operation
  639. * @ Access private
  640. * @ Param string $ query SQL command
  641. * @ Return boolen returns false if it is a query operation.
  642. */
  643. Static function isMainIps ($ query ){
  644. $ QueryIps = 'Insert | UPDATE | DELETE | REPLACE | CREATE | DROP | load data | SELECT. * INTO | COPY | ALTER | GRANT | REVOKE | LOCK | unlock ';
  645. If (preg_match ('/^ \ s *"? ('. $ QueryIps.') \ s +/I ', $ query )){
  646. Return true;
  647. }
  648. Return false;
  649. }
  650. /**
  651. * Filter POST submitted data
  652. * @ Access private
  653. * @ Param mixed $ data POST submit data
  654. * @ Param string $ table data table name
  655. * @ Return mixed $ newdata
  656. */
  657. Static function filterPost ($ table, $ data ){
  658. $ Table_column = self: getFields ($ table );
  659. $ Newdata = array ();
  660. Foreach ($ table_column as $ key => $ val ){
  661. If (array_key_exists ($ key, $ data) & ($ data [$ key])! = ''){
  662. $ Newdata [$ key] = $ data [$ key];
  663. }
  664. }
  665. Return $ newdata;
  666. }
  667. /**
  668. * Start the transaction
  669. * @ Access function
  670. * @ Return void
  671. */
  672. Static function startTrans (){
  673. // Data rollback support
  674. $ Link = self: $ link;
  675. If (! $ Link) return false;
  676. If (self: $ transTimes = 0 ){
  677. $ Link-> beginTransaction ();
  678. }
  679. Self: $ transTimes ++;
  680. Return;
  681. }
  682. /**
  683. * Used for querying and submitting under the non-automatic submission status
  684. * @ Access function
  685. * @ Return boolen
  686. */
  687. Static function commit (){
  688. $ Link = self: $ link;
  689. If (! $ Link) return false;
  690. If (self ::$ transTimes> 0 ){
  691. $ Result = $ link-> commit ();
  692. Self: $ transTimes = 0;
  693. If (! $ Result ){
  694. Self: throw_exception (self: $ error ());
  695. Return false;
  696. }
  697. }
  698. Return true;
  699. }
  700. /**
  701. * Transaction rollback
  702. * @ Access function
  703. * @ Return boolen
  704. */
  705. Public function rollback (){
  706. $ Link = self: $ link;
  707. If (! $ Link) return false;
  708. If (self ::$ transTimes> 0 ){
  709. $ Result = $ link-> rollback ();
  710. Self: $ transTimes = 0;
  711. If (! $ Result ){
  712. Self: throw_exception (self: $ error ());
  713. Return false;
  714. }
  715. }
  716. Return true;
  717. }

  718. /**

  719. * Handle errors
  720. * @ Access function
  721. * @ Return void
  722. */
  723. Static function throw_exception ($ err ){
  724. Echo'

    ERROR: '. $ err .'

    ';
  725. }
  726. }

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.