New PDO database Operation class PHP version (MySQL only) _php tutorial

Source: Internet
Author: User
Copy CodeThe code is as follows:
/**
* Author: Hu Rui
* Date: 2012/07/21
* e-mail: hooray0905@foxmail.com
*/

Class hrdb{
protected $pdo;
protected $res;
protected $config;

/* Constructor function */
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 results into Stdclass
$this->pdo->setattribute (Pdo::attr_default_fetch_mode, pdo::fetch_obj);
Write your own code capture exception
$this->pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
}

/* Database off */
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 to turn on debug, output SQL statement on
* 0 does not open
* 1 Open
* 2 Open and terminate the program
* int $mode return type
* 0 returns multiple records
* 1 Returns a single record
* 2 Number of rows returned
* String/array $table database table, two kinds of value-transfer modes
* Normal Mode:
* ' Tb_member, Tb_money '
* Array Mode:
* Array (' tb_member ', ' Tb_money ')
* String/array $fields database fields that need to be queried, allowed to be empty, default to find all, two modes of pass value
* Normal Mode:
* ' Username, password '
* Array Mode:
* Array (' username ', ' password ')
* String/array $sqlwhere query condition, allow NULL, two modes of transmission value
* Normal Mode:
* ' and type = 1 and username like "%os%" '
* Array Mode:
* Array (' type = 1 ', ' username like '%os% "')
* String $orderby Sort, default to reverse ID
*/
Public Function Select ($debug, $mode, $table, $fields = "*", $sqlwhere = "", $orderby = "Tbid desc") {
Parameter handling
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 to turn on debug, output SQL statement on
* 0 does not open
* 1 Open
* 2 Open and terminate the program
* int $mode return type
* 0 no return information
* 1 Returns the number of execution entries
* 2 Returns the ID of the last inserted record
* String/array $table database table, two kinds of value-transfer modes
* Normal Mode:
* ' Tb_member, Tb_money '
* Array Mode:
* Array (' tb_member ', ' Tb_money ')
* String/array $set need to insert the field and content, two modes of transmission value
* 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 handling
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 to turn on debug, output SQL statement on
* 0 does not open
* 1 Open
* 2 Open and terminate the program
* int $mode return type
* 0 no return information
* 1 Returns the number of execution entries
* String $table database table, two modes of transfer value
* Normal Mode:
* ' Tb_member, Tb_money '
* Array Mode:
* Array (' tb_member ', ' Tb_money ')
* String/array $set need to update the fields and content, two types of value-transfer mode
* Normal Mode:
* ' username = ' Test ', type = 1, dt = Now () '
* Array Mode:
* Array (' username = ' test ' ', ' type = 1 ', ' dt = Now () ')
* String/array $sqlwhere Modify condition, allow null, two modes of transmission value
* 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 handling
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 to turn on debug, output SQL statement on
* 0 does not open
* 1 Open
* 2 Open and terminate the program
* int $mode return type
* 0 no return information
* 1 Returns the number of execution entries
* String $table database table
* String/array $sqlwhere Delete condition, allow null, two modes of transfer value
* 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 handling
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 use, and before the difference is not small, the purpose is to facilitate the transplant.

This rewrite focuses on several issues:

①insert statement is too complex, fields and values correspond prone to errors

Let's take a look at the most common sentence of SQL INSERT statement

Copy CodeThe code is as follows: INSERT into Tb_member (username, type, dt) VALUES (' Test ', 1, now ())
In traditional mode, the fields and values parameters are passed in separately, but they are guaranteed to be in the same order as the arguments are passed in. This can easily lead to a sequence of confusion or a missing parameter.

This time has changed the problem, the use of MySQL's unique insert syntax, the same function as above, you can change the wording of this

Copy CodeThe code is as follows: INSERT INTO Tb_member set username = "Test", type = 1, Lastlogindt = Now ()
Just like update, at a glance.

② partial parameters can be replaced with an array

For example, a sentence like SQL

Copy CodeThe code is as follows: Delete from Tb_member where 1=1 and tbid = 1 and username = "Hooray"
When the method was originally called, it was necessary to manually assemble the where condition, so the cost of the operation is very high, and now it can be used in this form
Copy CodeThe code is as follows:
$where = Array (
' Tbid = 1 ',
' username = ' Hooray '
);
$db->delete (1, 0, ' Tb_member ', $where);

No number of conditions will disturb your thinking. Again, not just the where parameter, the set in update can also be in this form (see full source for details)

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 is too complex to be able to use the methods provided in the class to assemble SQL statements, and this is a function that can pass directly to the SQL statement I have assembled and return the information. Now, this feature also has a

Copy CodeThe code is as follows:
$db->query (' Select username, password from tb_member ');
$rs = $db->fetchall ();

Is it much like the original eco-notation of PDO?

④ support for creating multiple database connections

Originally because only the database operation method, so does not support the multi-database connection, in the implementation need to replicate 2 identical files, modify some variables, operation is complex. Now the problem is 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=hoorayos2 ',
' Name ' = ' root ',
' Password ' = ' Hooray '
);
$db 2 = new Hrdb ($db _hoorayos_config2);

This enables the creation of 2 database connections at the same time, which facilitates the processing of database interactions with the database.

The general new features are so many, the whole code is not much, welcome to read about. Here is the test code I wrote when writing, but also provide up, easy to learn.

Copy CodeThe code is as follows:
Require_once (' global.php ');
Require_once (' inc/setting.inc.php ');

$db = new Hrdb ($db _hoorayos_config);

Echo ' Select Test';
Echo ' Normal mode, direct string incoming
';
$rs = $db->select (1, 0, ' tb_member ', ' username, password ', ' and type = 1 and username like "%os%" ');
Echo '
Array pattern, which can be passed in an array
';
$fields = Array (' username ', ' password ');
$where = Array (' type = 1 ', ' username like '%os% ');
$rs = $db->select (1, 0, ' Tb_member ', $fields, $where);

Echo ' Insert Test';
Echo ' Normal mode, direct string incoming
';
$db->insert (1, 0, ' tb_member ', ' username = ' Test ', type = 1, Lastlogindt = Now () ');
Echo '
Array pattern, which can be passed in an array
';
$set = Array (' username = ' test ' ', ' type = 1 ', ' Lastlogindt = Now () ');
$db->insert (1, 0, ' Tb_member ', $set);

Echo ' Update Test';
Echo ' Normal mode, direct string incoming
';
$db->update (1, 0, ' tb_member ', ' username = ' 123 ', type = 1, Lastlogindt = Now () ', ' and tbid = 7 ');
Echo '
Array pattern, which can be passed in an array
';
$set = Array (' username = "123" ', ' type = 1 ', ' Lastlogindt = Now () ');
$where = Array (' tbid = 1 ');
$db->update (1, 0, ' Tb_member ', $set, $where);

Echo ' Delete Test';
Echo ' Normal mode, direct string incoming
';
$db->delete (1, 0, ' tb_member ', ' and tbid = 1 and username = "Hooray");
Echo '
Array pattern, which can be passed in an array
';
$where = Array (
' Tbid = 1 ',
' username = ' Hooray '
);
$db->delete (1, 0, ' Tb_member ', $where);

Echo ' Custom SQL';
$db->query (' Select username, password from tb_member ');
$rs = $db->fetchall ();
Var_dump ($RS);

$db->close ();

Author: Hu Yuan

http://www.bkjia.com/PHPjc/325810.html www.bkjia.com true http://www.bkjia.com/PHPjc/325810.html techarticle Copy the code code as follows:/** * Author: Hu Rui * Date: 2012/07/21 * Email: hooray0905@foxmail.com */class hrdb{protected $pdo; protected $res; prot ected $config; /* Construction Letter ...

  • 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.