Brand new PDO database operation php version (For Mysql only)

Source: Internet
Author: User
Tags dsn

Copy codeThe Code is as follows :/**
* Author: Hu Rui
* Date:
* Email: hooray0905@foxmail.com
*/

Class HRDB {
Protected $ pdo;
Protected $ res;
Protected $ config;

/* Constructor */
Function _ construct ($ config ){
$ This-> Config = $ config;
$ This-> connect ();
}

/* Database connection */
Public function connect (){
$ This-> pdo = new PDO ($ this-> Config ['dsn '], $ this-> Config ['name'], $ this-> Config ['Password']);
$ This-> pdo-> query ('set names utf8 ;');
// Serialize the result to stdClass
// $ This-> pdo-> setAttribute (PDO: ATTR_DEFAULT_FETCH_MODE, PDO: FETCH_OBJ );
// Write your own code to catch Exception
$ This-> pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
}

/* Shut down the database */
Public function close (){
$ This-> pdo = null;
}

Public function query ($ SQL ){
$ Res = $ this-> pdo-> query ($ SQL );
If ($ res ){
$ This-> res = $ res;
}
}
Public function exec ($ SQL ){
$ Res = $ this-> pdo-> exec ($ SQL );
If ($ res ){
$ This-> res = $ res;
}
}
Public function fetchAll (){
Return $ this-> res-> fetchAll ();
}
Public function fetch (){
Return $ this-> res-> fetch ();
}
Public function fetchColumn (){
Return $ this-> res-> fetchColumn ();
}
Public function lastInsertId (){
Return $ this-> res-> lastInsertId ();
}

/**
* Parameter description
* Int $ debug: whether debugging is enabled. If debugging is enabled, an SQL statement is output.
* 0: Disabled
* 1. Enable
* 2 enable and terminate the program
* Int $ mode return type
* Multiple records are returned at 0.
* 1 return a single record
* 2 Number of returned rows
* String/array $ table database table, two value passing Modes
* Normal Mode:
* 'Tb _ member, tb_money'
* Array mode:
* Array ('tb _ member ', 'tb _ money ')
* String/array $ fields of the database to be queried, which can be null. The default value is to search for all fields. Two value passing modes are available.
* Normal Mode:
* 'Username, password'
* Array mode:
* Array ('username', 'Password ')
* String/array $ sqlwhere query condition, which can be null. Two value passing modes are supported.
* Normal Mode:
* 'And type = 1 and username like "% OS % "'
* Array mode:
* Array ('Type = 1', 'username like "% OS % "')
* String $ orderby sorting, id reverse by default
*/
Public function select ($ debug, $ mode, $ table, $ fields = "*", $ sqlwhere = "", $ orderby = "tbid desc "){
// Parameter Processing
If (is_array ($ table )){
$ Table = implode (',', $ table );
}
If (is_array ($ fields )){
$ Fields = implode (',', $ fields );
}
If (is_array ($ sqlwhere )){
$ Sqlwhere = 'and'. implode ('and', $ sqlwhere );
}
// Database operations
If ($ debug = 0 ){
If ($ mode = 2 ){
$ This-> query ("select count (tbid) from $ table where 1 = 1 $ sqlwhere ");
$ Return = $ this-> fetchColumn ();
} Else if ($ mode === 1 ){
$ This-> query ("select $ fields from $ table where 1 = 1 $ sqlwhere order by $ orderby ");
$ Return = $ this-> fetch ();
} Else {
$ This-> query ("select $ fields from $ table where 1 = 1 $ sqlwhere order by $ orderby ");
$ Return = $ this-> fetchAll ();
}
Return $ return;
} Else {
If ($ mode = 2 ){
Echo "select count (tbid) from $ table where 1 = 1 $ sqlwhere ";
} Else if ($ mode === 1 ){
Echo "select $ fields from $ table where 1 = 1 $ sqlwhere order by $ orderby ";
}
Else {
Echo "select $ fields from $ table where 1 = 1 $ sqlwhere order by $ orderby ";
}
If ($ debug = 2 ){
Exit;
}
}
}

/**
* Parameter description
* Int $ debug: whether debugging is enabled. If debugging is enabled, an SQL statement is output.
* 0: Disabled
* 1. Enable
* 2 enable and terminate the program
* Int $ mode return type
* 0 No returned information
* 1. Number of execution entries returned
* 2 return the id of the last inserted record
* String/array $ table database table, two value passing Modes
* Normal Mode:
* 'Tb _ member, tb_money'
* Array mode:
* Array ('tb _ member ', 'tb _ money ')
* String/array $ set: the fields and content to be inserted. Two value transmission modes are available.
* Normal Mode:
* 'Username = "test", type = 1, dt = now ()'
* Array mode:
* Array ('username = "test" ', 'Type = 1', 'dt = now ()')
*/
Public function insert ($ debug, $ mode, $ table, $ set ){
// Parameter Processing
If (is_array ($ table )){
$ Table = implode (',', $ table );
}
If (is_array ($ set )){
$ Set = implode (',', $ set );
}
// Database operations
If ($ debug = 0 ){
If ($ mode = 2 ){
$ This-> query ("insert into $ table set $ set ");
$ Return = $ this-> lastInsertId ();
} Else if ($ mode === 1 ){
$ This-> exec ("insert into $ table set $ set ");
$ Return = $ this-> res;
} Else {
$ This-> query ("insert into $ table set $ set ");
$ Return = NULL;
}
Return $ return;
} Else {
Echo "insert into $ table set $ set ";
If ($ debug = 2 ){
Exit;
}
}
}

/**
* Parameter description
* Int $ debug: whether debugging is enabled. If debugging is enabled, an SQL statement is output.
* 0: Disabled
* 1. Enable
* 2 enable and terminate the program
* Int $ mode return type
* 0 No returned information
* 1. Number of execution entries returned
* String $ table database table, two value passing Modes
* Normal Mode:
* 'Tb _ member, tb_money'
* Array mode:
* Array ('tb _ member ', 'tb _ money ')
* String/array $ set fields and content to be updated. Two value transmission modes are available.
* Normal Mode:
* 'Username = "test", type = 1, dt = now ()'
* Array mode:
* Array ('username = "test" ', 'Type = 1', 'dt = now ()')
* String/array $ sqlwhere condition for modification, which can be null. Two value passing modes are supported.
* Normal Mode:
* 'And type = 1 and username like "% OS % "'
* Array mode:
* Array ('Type = 1', 'username like "% OS % "')
*/
Public function update ($ debug, $ mode, $ table, $ set, $ sqlwhere = ""){
// Parameter Processing
If (is_array ($ table )){
$ Table = implode (',', $ table );
}
If (is_array ($ set )){
$ Set = implode (',', $ set );
}
If (is_array ($ sqlwhere )){
$ Sqlwhere = 'and'. implode ('and', $ sqlwhere );
}
// Database operations
If ($ debug = 0 ){
If ($ mode = 1 ){
$ This-> exec ("update $ table set $ set where 1 = 1 $ sqlwhere ");
$ Return = $ this-> res;
} Else {
$ This-> query ("update $ table set $ set where 1 = 1 $ sqlwhere ");
$ Return = NULL;
}
Return $ return;
} Else {
Echo "update $ table set $ set where 1 = 1 $ sqlwhere ";
If ($ debug = 2 ){
Exit;
}
}
}

/**
* Parameter description
* Int $ debug: whether debugging is enabled. If debugging is enabled, an SQL statement is output.
* 0: Disabled
* 1. Enable
* 2 enable and terminate the program
* Int $ mode return type
* 0 No returned information
* 1. Number of execution entries returned
* String $ table database table
* String/array $ sqlwhere deletion condition, which can be null. Two value passing modes are supported.
* Normal Mode:
* 'And type = 1 and username like "% OS % "'
* Array mode:
* Array ('Type = 1', 'username like "% OS % "')
*/
Public function delete ($ debug, $ mode, $ table, $ sqlwhere = ""){
// Parameter Processing
If (is_array ($ sqlwhere )){
$ Sqlwhere = 'and'. implode ('and', $ sqlwhere );
}
// Database operations
If ($ debug = 0 ){
If ($ mode = 1 ){
$ This-> exec ("delete from $ table where 1 = 1 $ sqlwhere ");
$ Return = $ this-> res;
} Else {
$ This-> query ("delete from $ table where 1 = 1 $ sqlwhere ");
$ Return = NULL;
}
Return $ return;
} Else {
Echo "delete from $ table where 1 = 1 $ sqlwhere ";
If ($ debug = 2 ){
Exit;
}
}
}
}

In fact, the usage is not much different from the previous one. The purpose is to facilitate the migration.

This rewrite focuses on several issues:

① The insert statement is too complex, and the correspondence between fields and values is prone to errors.

Let's take a look at the most common SQL insert statement.

Copy codeThe Code is as follows: insert into tb_member (username, type, dt) values ('test', 1, now ())

In the traditional mode, fields and values parameters are passed in separately, but they must be consistent in the input order. This can easily lead to disordered order or missing a parameter.

The problem has been modified this time, and the insert syntax exclusive to mysql is used. It is also the above function, so you can replace it with this syntax.

Copy codeThe Code is as follows: insert into tb_member set username = "test", type = 1, lastlogindt = now ()

Just like update.

② Some parameters can be replaced by arrays.

For example

Copy codeThe Code is as follows: delete from tb_member where 1 = 1 and tbid = 1 and username = "hooray"

When calling a method, you need to manually assemble the where condition. This operation is costly and can be used now.Copy codeThe Code is as follows: $ where = array (
'Tbid = 1 ',
'Username = "hooray "'
);
$ Db-> delete (1, 0, 'tb _ member ', $ where );

If there are more conditions, your thinking will not be disrupted. Similarly, not only the where parameter, set in update can also be in this form (for details, see the complete source code)

Copy codeThe Code is as follows: $ set = array ('username = "123" ', 'Type = 1', 'lastlogindt = now ()');
$ Where = array ('tbid = 1 ');
$ Db-> update (1, 0, 'tb _ member ', $ set, $ where );

③ Customizable SQL statements

Sometimes, SQL statements are too complex to assemble SQL statements using the methods provided in the class. In this case, a function is required to directly import the assembled SQL statements for execution, and return information. Now, this feature is available.

Copy codeThe Code is as follows: $ db-> query ('select username, password from tb_member ');
$ Rs = $ db-> fetchAll ();

Is it similar to the original pdo style?

④ Support creating multi-database connections

Because it was only a database operation method, it does not support multi-database connections. in implementation, we need to copy two identical files and modify some variables. The operation is complex. Now this problem has been solved.

Copy codeThe Code is as follows: $ db_hoorayos_config = array (
'Dsn '=> 'mysql: host = localhost; dbname = hoorayos ',
'Name' => 'root ',
'Password' => 'hooray'
);
$ Db = new HRDB ($ db_hoorayos_config );

$ Db_hoorayos_config2 = array (
'Dsn '=> 'mysql: host = localhost; dbname = hoorayoss ',
'Name' => 'root ',
'Password' => 'hooray'
);
$ Db2 = new HRDB ($ db_hoorayos_config2 );

In this way, two database connections can be created at the same time to facilitate the interaction between the database and the database.

There are so many new features and there are not many codes. Read more. The following is the test code that I wrote during writing, which is also provided for your convenience.

Copy codeThe Code is as follows: require_once ('Global. php ');
Require_once ('inc/setting. inc. php ');

$ Db = new HRDB ($ db_hoorayos_config );

Echo 'Echo 'normal mode, direct string input <br> ';
$ Rs = $ db-> select (1, 0, 'tb _ member', 'username, password ', 'and type = 1 and username like "% OS % "');
Echo '<br> array mode, which can be input <br> ';
$ Fields = array ('username', 'Password ');
$ Where = array ('Type = 1', 'username like "% OS % "');
$ Rs = $ db-> select (1, 0, 'tb _ member ', $ fields, $ where );

Echo 'Echo 'normal mode, direct string input <br> ';
$ Db-> insert (1, 0, 'tb _ member', 'username = "test", type = 1, lastlogindt = now ()');
Echo '<br> array mode, which can be input <br> ';
$ Set = array ('username = "test" ', 'Type = 1', 'lastlogindt = now ()');
$ Db-> insert (1, 0, 'tb _ member ', $ set );

Echo 'Echo 'normal mode, direct string input <br> ';
$ Db-> update (1, 0, 'tb _ member', 'username = "123", type = 1, lastlogindt = now ()', 'and tbid = 7 ');
Echo '<br> array mode, which can be input <br> ';
$ Set = array ('username = "123" ', 'Type = 1', 'lastlogindt = now ()');
$ Where = array ('tbid = 1 ');
$ Db-> update (1, 0, 'tb _ member ', $ set, $ where );

Echo 'Echo 'normal mode, direct string input <br> ';
$ Db-> delete (1, 0, 'tb _ member ',' and tbid = 1 and username = "hooray "');
Echo '<br> array mode, which can be input <br> ';
$ Where = array (
'Tbid = 1 ',
'Username = "hooray "'
);
$ Db-> delete (1, 0, 'tb _ member ', $ where );

Echo '$ Db-> query ('select username, password from tb_member ');
$ Rs = $ db-> fetchAll ();
Var_dump ($ rs );

$ Db-> close ();

Author: Hu yunrui

Related Article

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.