Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a New PDO Database Operation Class by php

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how php to achieve the new PDO database operation class, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

The code is as follows:

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 capture Exception

$this- > pdo- > setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)

}

/ * Database shutdown * /

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

* whether int $debug enables debugging. If it is enabled, the sql statement is output.

* 0 is not enabled

* 1 enable

* 2 start and terminate the program

* int $mode return type

* 0 returns multiple records

* 1 return a single record

* 2 number of rows returned

* string/array $table database table, two value transfer modes

* normal mode:

* 'tb_member, tb_money'

* Array mode:

* array ('tb_member',' tb_money')

* the database field to be queried by string/array $fields. It is allowed to be empty, and the default is to find all. There are two value transfer modes.

* normal mode:

* 'username, password'

* Array mode:

* array ('username',' password')

* string/array $sqlwhere query condition, which is allowed to be empty. There are two value passing modes.

* normal mode:

* 'and type = 1 and username like "% os%"'

* Array mode:

* array ('type = 1,' username like "% os%")

* string $orderby sort, default is id reverse order

, /

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 operation

If ($debug = = 0) {

If ($mode = = 2) {

$this- > query ("select count (tbid) from $table where 1$ sqlwhere")

$return = $this- > fetchColumn ()

} else if ($mode = 1) {

$this- > query ("select $fields from $table where 1$ sqlwhere orderby $orderby")

$return = $this- > fetch ()

} else {

$this- > query ("select $fields from $table where 1$ sqlwhere orderby $orderby")

$return = $this- > fetchAll ()

}

Return $return

} else {

If ($mode = = 2) {

Echo "select count (tbid) from $table where 1$ sqlwhere"

} else if ($mode = 1) {

Echo "select $fields from $table where 1$ sqlwhere orderby $orderby"

}

Else {

Echo "select $fields from $table where 1$ sqlwhere orderby $orderby"

}

If ($debug = = 2) {

Exit

}

}

}

/ * *

* Parameter description

* whether int $debug enables debugging. If it is enabled, the sql statement is output.

* 0 is not enabled

* 1 enable

* 2 start 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 record inserted

* string/array $table database table, two value transfer modes

* normal mode:

* 'tb_member, tb_money'

* Array mode:

* array ('tb_member',' tb_money')

* fields and contents to be inserted in string/array $set, two value transfer modes

* 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 operation

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

* whether int $debug enables debugging. If it is enabled, the sql statement is output.

* 0 is not enabled

* 1 enable

* 2 start and terminate the program

* int $mode return type

* 0 No return information

* 1 returns the number of execution entries

* string $table database table, two value transfer modes

* normal mode:

* 'tb_member, tb_money'

* Array mode:

* array ('tb_member',' tb_money')

* fields and contents to be updated for string/array $set, two value transfer modes

* normal mode:

* 'username = "test", type = 1, dt = now ()'

* Array mode:

* array ('username = "test"', 'type = 1','dt = now ()')

* string/array $sqlwhere modifies the condition. It is allowed to be empty. There are two kinds of value passing modes.

* 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 operation

If ($debug = = 0) {

If ($mode = = 1) {

$this- > exec ("update $table set $set where 1$ sqlwhere")

$return = $this- > res

} else {

$this- > query ("update $table set $set where 1$ sqlwhere")

$return = NULL

}

Return $return

} else {

Echo "update $table set $set where 1$ sqlwhere"

If ($debug = = 2) {

Exit

}

}

}

/ * *

* Parameter description

* whether int $debug enables debugging. If it is enabled, the sql statement is output.

* 0 is not enabled

* 1 enable

* 2 start 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. It is allowed to be empty. There are two value passing modes.

* 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 operation

If ($debug = = 0) {

If ($mode = = 1) {

$this- > exec ("delete from $table where 1$ sqlwhere")

$return = $this- > res

} else {

$this- > query ("delete from $table where 1$ sqlwhere")

$return = NULL

}

Return $return

} else {

Echo "delete from $table where 1$ sqlwhere"

If ($debug = = 2) {

Exit

}

}

}

}

In fact, in use, it is not much different from the previous one, and the purpose is to facilitate transplantation.

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 insertion statement

The copy 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 separately, but make sure that the two parameters are passed in the same order. This can easily lead to out of order or omission of a parameter.

This time the problem has been modified, using the insert syntax unique to mysql, and the same function as above can be written in this way.

The copy code is as follows:

Insert into tb_member set username = "test", type = 1, lastlogindt = now ()

Just like update, it's clear at a glance.

Some parameters of ② can be replaced by arrays.

For example, the sentence "sql"

The copy code is as follows:

Delete from tb_member where 1, 1 and tbid = 1 and username = "hooray"

In the past, when the method was called, the where condition needed to be assembled manually, so the operation was very expensive, and now it can be used in this form.

The copy code is as follows:

$where = array (

'tbid = 1'

'username = "hooray"'

);

$db- > delete (1,0, 'tb_member', $where)

No matter how many conditions will not disturb your train of thought. Similarly, not only the where parameter, but also the set in update can be in this form (see the complete source code for details)

The copy 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 statement

Sometimes, sql is too complex to assemble sql statements using the methods provided in the class, so you need a function that can directly pass in the sql statements that I have assembled for execution and return information. Now, this function is also available.

The copy code is as follows:

$db- > query ('select username, password from tb_member')

$rs = $db- > fetchAll ()

Is it very similar to the original way of writing pdo?

④ supports the creation of multiple database connections

Because the original method is only a database operation method, it does not support multiple database connections. In implementation, two identical files need to be copied and some variables need to be modified, which is a complicated operation. Now the problem has been solved.

The copy 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'

);

$db2 = new HRDB ($db_hoorayos_config2)

In this way, two database connections can be created at the same time, which is convenient to deal with the interaction between the database and the database.

Roughly there are so many new features, the whole code is not much, welcome to read and understand. The following is the test code I wrote when I wrote it, and it is also provided to facilitate everyone to learn.

The copy 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 passing in

'

$rs = $db- > select (1,0, 'tb_member',' username, password', 'and type = 1 and username like "% os%"')

Echo'

Array mode, 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 passing in

'

$db- > insert (1,0, 'tb_member',' username = "test", type = 1, lastlogindt = now ()')

Echo'

Array mode, 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 passing in

'

$db- > update (1,0, 'tb_member',' username = "123", type = 1, lastlogindt = now ()', 'and tbid = 7')

Echo'

Array mode, 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 passing in

'

$db- > delete (1,0, 'tb_member',' and tbid = 1 and username = "hooray"')

Echo'

Array mode, 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 ()

These are all the contents of the article "how php implements the new PDO database operation class". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report