A pdo class is encapsulated. We hope that the CSDN experts can guide 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, comeon !? Php *** PDO encapsulation class to make it easier to use * modifyDate: 2014-07-01 * classPDOX {private $ pdonull; public $ statem

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, comeon! ? Php/*** PDO encapsulation class, designed to make it easier to use * modifyDate: 2014-07-01 */classPDOX {private $ pdo = null; public $ statem

Encapsulates a PDO class. We hope that the CSDN experts will give you some advice on the shortcomings.
A pdo class is encapsulated. We hope that the CSDN experts will give you some advice on the shortcomings.

Masters, come on!

 /**
* The PDO encapsulation class is designed for ease of use.
* Modify Date: 2014-07-01
*/
Class PDOX {
Private $ pdo = null;

Public $ statement = null;

Public $ options = array (
PDO: MYSQL_ATTR_INIT_COMMAND => "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 column name format and error message type. You can use numbers or parameters directly.
*/
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 generate a compiled SQL statement template? : Name format
Returns a statement object.
*/
Public function prepare ($ SQL ){
If (empty ($ SQL )){
Return false;
}
$ This-> statement = $ this-> pdo-> prepare ($ SQL );
Return $ this-> statement;
}
/**
Execute SQL statements, which are 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 the chained operation to obtain data through the encapsulated operation of 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 ();
}
/**
Commit transactions
*/
Public function commit (){
Return $ this-> pdo-> commit ();
}
/**
Transaction rollback
*/
Public function rollBack (){
Return $ this-> pdo-> rollBack ();
}

Public function lastInertId (){
Return $ this-> pdo-> lastInsertId ();
}


// ** PDOStatement class operation encapsulation **//

/**
Let the template Execute SQL statements. 1. Execute the 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 of which have (index, Association)
PDO: FETCH_ASSOC associated array
PDO: FETCH_NUM Index
PDO: FETCH_OBJ object
The PDO: FETCH_LAZY object carries the queryString query SQL statement.
PDO: FETCH_BOUND this parameter is used if bindColumn is set.
*/
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 of which have (index, Association)
PDO: FETCH_ASSOC associated array
PDO: FETCH_NUM Index
PDO: FETCH_OBJ object
PDO: FETCH_COLUMN specifies the column parameter 2. You can specify the column to be obtained.
PDO: FETCH_CLASS specifies the defined class
PDO: FETCH_FUNC custom class to process returned data
PDO_FETCH_BOUND this parameter is used if you need to set bindColumn
Parameter 2 Description:
Specifies the class or function to process the result.
*/
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 );
}
/**
The returned results in the form of objects are the same as those in fetch (PDO: FETCH_OBJ ).
*/
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-> bindColumn ()
}
*/

/**
Bind variables to placeholders as references (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 = '';
[This article from the Internet (http://www.68idc.cn)] break;
}
Return $ this-> statement-> bindParam ($ parameter, $ variable, $ data_type, $ length );
}

/**
Returns the number of rows in the statement record set.
*/
Public 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 function closeCursor (){
Return $ this-> statement-> closeCursor ();
}
/**
The returned error message also contains the error number.
*/
Private function errorInfo (){
Return $ this-> statement-> errorInfo ();
}
/**
Error Code returned
*/
Private function errorCode (){
Return $ this-> statement-> errorCode ();
}



// Simplify the operation
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.
------ 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.

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.