Encapsulates a PDO class. we hope that the CSDN experts will give you some advice on the shortcomings.

Source: Internet
Author: User
It encapsulates a PDO class. we hope that the CSDN experts will give you some advice on the shortcomings and encapsulate a PDO class. we hope that the CSDN experts will give you some advice on the shortcomings.

Masters, come on!

 "Set names",); public function _ construct ($ dsn, $ user = '', $ pass ='', $ persistent = false, $ charset = "utf8 ") {$ this-> options [PDO: MYSQL_ATTR_INIT_COMMAND]. = $ charset; if ($ persistent) {$ this-> options [PDO: ATTR_PERSISTENT] = true ;}$ this-> pdo = new PDO ($ dsn, $ user, $ pass, $ this-> options);}/** global attribute settings, including: the column name format and error message type can use numbers or the parameter */public function setAttr ($ param, $ val = '') {if (is_array ($ param) {foreach ($ Param as $ key => $ val) {$ this-> pdo-> setAttribute ($ key, $ val) ;}} else {if ($ val! = '') {$ This-> pdo-> setAttribute ($ param, $ val);} else {return false ;}}} /** can you use to generate a compiled SQL statement template?: Name: return a statement object */public function prepare ($ SQL) {if (empty ($ SQL) {return false ;} $ this-> statement = $ this-> pdo-> prepare ($ SQL); return $ this-> statement;}/** run the SQL statement, it is generally used to add, delete, update, or set the number of rows affected by the returned results */public function exec ($ SQL) {if (empty ($ SQL) {return false ;} try {return $ this-> pdo-> exec ($ SQL);} catch (Exception $ e) {return $ e-> getMessage ();}} /** execute a query with a returned value. if PDOStatement is returned, you can use a chained operation to obtain data through the operation encapsulated in this class */public function Query ($ SQL) {if (empty ($ SQL) {return false;} $ this-> statement = $ this-> pdo-> query ($ SQL ); return $ this-> statement;}/** start transaction */public function beginTransaction () {return $ this-> pdo-> beginTransaction ();} /** submit the transaction */public function commit () {return $ this-> pdo-> commit ();}/** transaction rollBack */public function rollBack () {return $ this-> pdo-> rollBack ();} public function lastInertId () {return $ this-> pdo-> lastInsertId ();} // ** PDOSta Tement class operation encapsulation ** // ** allows the template to execute SQL statements. 1. execute compiled statements. 2. Compile the statements during execution. */public function execute ($ param = "") {if (is_array ($ param) {try {return $ this-> statement-> execute ($ param);} catch (Exception $ e) {// return $ this-> errorInfo (); return $ e-> getMessage () ;}} else {try {return $ this-> statement-> execute ();} catch (Exception $ e) {/* returned error message format [0] => 42S22 [1] => 1054 [2] => Unknown column 'col' in 'Field list' return $ this-> errorInfo (); */Return $ e-> getMessage () ;}}/** parameter 1 description: PDO: FETCH_BOTH is also the default value. Both have (index, Association) PDO:: FETCH_ASSOC associated array PDO: FETCH_NUM index PDO: FETCH_OBJ object PDO: FETCH_LAZY object will attach queryString query SQL statement PDO: FETCH_BOUND if bindColumn is set, use this parameter */public function fetch ($ fetch_type = PDO: FETCH_ASSOC) {if (is_object ($ this-> statement )) {return $ this-> statement-> fetch ($ fetch_type);} return false;}/** parameter 1 description: PDO: FETCH_BOTH is also the default value, both have (index, Association) PDO: FETCH _ ASSOC associated array PDO: FETCH_NUM index PDO: FETCH_OBJ object PDO: FETCH_COLUMN specify column parameter 2 you can specify the column to be obtained PDO: FETCH_CLASS specify the defined class PDO :: the FETCH_FUNC custom class processes the returned data PDO_FETCH_BOUND. if you need to set bindColumn, use this parameter 2 description: given the class or function */public function fetchAll ($ fetch_type = PDO: FETCH_ASSOC, $ handle = '') {if (empty ($ handle )) {return $ this-> statement-> fetchAll ($ fetch_type);} return $ this-> statement-> fetchAll ($ fetch_type, $ handle );} /** return results and fetc in the form of objects H (PDO: FETCH_OBJ) same */public function fetchObject ($ class_name) {if (empty ($ clss_name) {return $ this-> statement-> fetchObject ();} return $ this-> statement-> fetchObject ($ class_name);} public function fetchColumn ($ intColumn = 0) {return $ this-> statement-> fetchColumn ($ intColumn );} /** public function bindColumn ($ array = array (), $ type = EXTR_OVERWRITE) {if (count ($ array)> 0) {extract ($ array, $ type);} // $ this-> statement-> B IndColumn ()} * // ** bind variables to placeholders as a reference (you can execute prepare only once and bindParam multiple times to achieve reuse) */public function bindParam ($ parameter, $ variable, $ data_type = 'str', $ length = 0) {switch ($ data_type) {case 'str ': $ data_type = PDO: PARAM_STR; break; case 'int': $ data_type = PDO: PARAM_INT; break; default: $ data_type = ''; break ;} return $ this-> statement-> bindParam ($ parameter, $ variable, $ data_type, $ length);}/** return the number of rows in the statement record set */pu Blic function rowCount () {return $ this-> statement-> rowCount ();} public function count () {return $ this-> statement-> rowCount ();} public function columnCount () {$ this-> statement-> execute (); return $ this-> statement-> columnCount ();} public function getColumnMeta ($ intColumn) {return $ this-> statement-> getColumnMeta ($ intColumn);}/** close */public function close () {return $ this-> statement-> closeCursor ();} public functio N closeCursor () {return $ this-> statement-> closeCursor ();}/** the error message returned also includes the error code */private function errorInfo () {return $ this-> statement-> errorInfo ();}/** error code returned */private function errorCode () {return $ this-> statement-> errorCode () ;}// simplify the operation of public function insert ($ table, $ data) {if (! Is_array ($ data) {return false;} $ cols = array (); $ vals = array (); foreach ($ data as $ key => $ val) {$ cols [] = $ key; $ vals [] = "'". $ val. "'" ;}$ SQL = "insert into {$ table} ("; $ SQL. = implode (",", $ cols ). ") VALUES ("; $ SQL. = implode (",", $ vals ). ")"; return $ this-> exec ($ SQL);} public function insertBind ($ table, $ arrayData) {if (! Is_array ($ arrayData) {return false;} $ vals = array_keys ($ arrayData); $ cols = array ();/* $ arrayobject = new ArrayObject ($ arrayData ); $ iterator = $ arrayobject-> getIterator (); while ($ iterator-> valid () {$ vals [] = ':'. $ iterator-> key (). ''; $ iterator-> next () ;}*/$ c = implode ('', $ vals); $ cols = array_filter (explode (':', $ c); $ SQL = "insert into {$ table} ("; $ SQL. = implode (",", $ cols ). ") VALUES ("; $ SQL. = Implode (",", $ vals ). ")"; $ this-> statement = $ this-> pdo-> prepare ($ SQL); $ this-> statement-> execute ($ arrayData ); return $ this-> statement-> rowCount ();} public function update ($ table, $ data, $ where) {if (! Is_array ($ data) {return false;} $ set = array (); foreach ($ data as $ key => $ val) {$ set [] = $ key. "= '". $ val. "'" ;}$ SQL = "UPDATE {$ table} SET"; $ SQL. = implode (",", $ set); $ SQL. = "WHERE ". $ where; return $ this-> exec ($ SQL);} public function updateBind ($ SQL, $ arrayWhere) {if (empty ($ SQL) |! Is_array ($ arrayWhere) {return false;} $ this-> statement = $ this-> pdo-> prepare ($ SQL ); $ this-> statement-> execute ($ arrayWhere); return $ this-> statement-> rowCount ();} public function delete ($ table, $ where) {if (empty ($ table) | empty ($ where) {return false;} $ SQL = "DELETE FROM {$ table} WHERE ". $ where; return $ this-> exec ($ SQL);} public function deleteBind ($ SQL, $ arrayWhere) {if (empty ($ SQL) |! Is_array ($ arrayWhere) {return false;} $ this-> statement = $ this-> pdo-> prepare ($ SQL ); $ this-> statement-> execute ($ arrayWhere); return $ this-> statement-> rowCount () ;}}?>




After all, in a project, it is impossible to write some of PDO's own stuff everywhere. Also, do not say that PDO has been encapsulated, and there is no need to package any other nonsense.


Reply to discussion (solution)

Suggestions:
1. if I
$ Db = new PDOX;
$ A = $ db-> query ($ sql1 );
$ B = $ db-> query ($ sql2 );
Print_r ($ a-> fetchall ());
Print_r ($ B-> fetchall ());
Yes? Obviously not, because
$ This-> statement = $ this-> pdo-> query ($ SQL );
The previous query result is overwritten by the last one.
2. Transaction operations should be encapsulated as a whole, and only a group of SQL statements should be passed in to hide related operations.
3. the stored procedure is not considered.
4. PDOX can directly inherit from PDO without copying the existing PDO method.


In general, it is not bad, but I feel that some methods are too cumbersome and can be integrated as necessary.

Suggestions:
1. if I
$ Db = new PDOX;
$ A = $ db-> query ($ sql1 );
$ B = $ db-> query ($ sql2 );
Print_r ($ a-> fetchall ());
Print_r ($ B-> fetchall ());
Yes? Obviously not, because
$ This-> statement = $ this-> pdo-> query ($ SQL );
The previous query result is overwritten by the last one.
2. Transaction operations should be encapsulated as a whole, and only a group of SQL statements should be passed in to hide related operations.
3. the stored procedure is not considered.
4. PDOX can directly inherit from PDO without copying the existing PDO method.


Thank you for your valuable comments. I just want to simplify it.
1. there are some solutions for this example.
2. I rarely use transactions and do not know how to encapsulate them. It would be better if you could give some advice.
3. stored procedures are rarely used.
4. copy the PDO method. I just want to use the PDO method, which is similar to that of PDO. it is convenient for friends who directly write PDO to use this method. You do not need to learn too much. Unlike other database classes, after learning the native database operations, you have to learn a new database operation again. it may be very simple, but learning also takes time.



In general, it is not bad, but I feel that some methods are too cumbersome and can be integrated as necessary.


How can integration be more concise ??

The purpose of encapsulation is to simplify the operation. if it is not commonly used, no encapsulation is required.

Class PDOX extends PDO {// execute various SQL commands and use the $ param parameter to extend the function query ($ SQL, $ param = null) {}// query and return single record function fetch ($ SQL) {}; // query and return multiple record function fetchall ($ SQL) {}} in array mode ){}}
Database classes can meet the needs of most applications as long as they have these three methods.
Because it is inherited from PDO, the original method of PDO will not be less

@ Xuzuning

$ Db = new PDOX;
$ A = $ db-> query ($ sql1 );
$ B = $ db-> query ($ sql2 );
Print_r ($ a-> fetchall ());
Print_r ($ B-> fetchall ());

Shouldn't there be too many programmers to write this code? In this case, you can consider giving up the support for this operation first. This is a big problem if my class has problems with efficiency or concurrency.

Is there any internal error or error in this category ??

Thank you for your speech.

Nested or recursive queries are often used to read the classification tree. how can this problem be solved?
Well, you don't need a message board.

Simple data insertion:
$ Data = array (': title' => $ title,': content' => $ content );
$ Pdo = new PDOX;
$ LastID = $ pdo-> insertBind ('article', $ data );


Modify data:
$ Data = array (': title' = >$ title,': ID' => $ id );
$ SQL = 'update article set title =: title where id =: ID ';
$ Yesorno = $ pdo-> updateBind ($ SQL, $ data );

Delete data:
$ Data = array (': ID' => $ id );
$ SQL = 'delete article where id =: ID ';
$ Yesorno = $ pdo-> deleteBind ($ SQL, $ data );

This method saves a lot of code. This is the key to writing this class.

Nested or recursive queries are often used to read the classification tree. how can this problem be solved?
Well, you don't need a message board.



What you said is actually used in recursion. If you want to use this class, pay attention to it.

I will try to optimize PHP code or use other methods to replace recursion, because recursion consumes resources.

Thank you for reminding me.

It means it looks quite tangled.

It means it looks quite tangled.



Tangled ???

I think it is convenient to operate data.

Let's continue ..

The purpose of encapsulation is to simplify the operation. if it is not commonly used, no encapsulation is required.

Class PDOX extends PDO {// execute various SQL commands and use the $ param parameter to extend the function query ($ SQL, $ param = null) {}// query and return single record function fetch ($ SQL) {}; // query and return multiple record function fetchall ($ SQL) {}} in array mode ){}}
Database classes can meet the needs of most applications as long as they have these three methods.
Because it is inherited from PDO, the original method of PDO will not be less



I don't know if the moderator can have a better PDO operation class ???
Can I contribute one.

No!
In addition, the preprocessing part is not encapsulated.

/*** Convert the array into an SQL statement * @ param array $ where the array to be generated * @ param string $ font connection string. */Final public function sqls ($ where, $ font = 'and') {# First save bindColumn $ this-> bindColumn = array (); if (is_array ($ where) {$ SQL = ''; foreach ($ where as $ key => $ val) {$ SQL. = $ SQL? "$ Font '$ key' =: $ key": "' $ key' =: $ key"; $ this-> bindColumn = array ($ key, $ val );} return;} else {return $ where ;}}

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.