


Brand new PDO database operation php version (only applicable to Mysql)_PHP tutorial
Jul 21, 2016 pm 03:17 PM
/**
* Author: Hu Rui
* Date: 2012/07/21
* Email: hooray0905@foxmail.com
*/
class HRDB{
protected $pdo;
protected $res;
protected $config;
/*構(gòu)造函數(shù)*/
function __construct($config){
$this->Config = $config;
$this->connect();
}
/*數(shù)據(jù)庫連接*/
public function connect(){
$this->pdo = new PDO($this->Config['dsn'], $this->Config['name'], $this->Config['password']);
$this->pdo->query('set names utf8;');
//把結(jié)果序列化成stdClass
//$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
//自己寫代碼捕獲Exception
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
/*數(shù)據(jù)庫關(guān)閉*/
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 enable debugging, if it is enabled, the sql statement will be output
* 0 Disable
* 1 Enable
* 2 Enable and terminate the program
* int $ mode return type
* 0 returns multiple records
* 1 returns a single record
* 2 returns the number of rows
* string/array $table database table, two value-passing modes
* normal Pattern:
* 'tb_member, tb_money'
* Array pattern:
* array('tb_member', 'tb_money')
* string/array $fields Database fields to be queried, allowed to be empty , the default is to search all, two value-passing modes
* Normal mode:
* 'username, password'
* Array mode:
* array('username', 'password')
* string/array $sqlwhere query conditions, empty allowed, two value-passing modes
* Normal mode:
* 'and type = 1 and username like "%os%"'
* Array mode :
* array('type = 1', 'username like "%os%"')
* string $orderby sorting, the default is id reverse order
*/
public function select($debug, $mode, $table, $fields="*", $sqlwhere="", $orderby="tbid desc"){
//參數(shù)處理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($fields)){
$fields = implode(', ', $fields);
}
if(is_array($sqlwhere)){
$sqlwhere = ' and '.implode(' and ', $sqlwhere);
}
//數(shù)據(jù)庫操作
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 enable debugging, if it is enabled, the sql statement will be output
* 0 Disable
* 1 Enable
* 2 Enable and terminate the program
* int $ mode return type
* 0 No return information
* 1 Return the number of execution entries
* 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 fields to be inserted and Content, two value-passing 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){
//參數(shù)處理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($set)){
$set = implode(', ', $set);
}
//數(shù)據(jù)庫操作
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 enable debugging, if it is enabled, the sql statement will be output
* 0 Disable
* 1 Enable
* 2 Enable and terminate the program
* int $ mode return type
* 0 No return information
* 1 Return number of execution entries
* 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 contents that need to be updated, two value-passing modes
* Normal mode:
* 'username = "test", type = 1, dt = now()'
* Array mode:
* array('username = "test"', 'type = 1', 'dt = now()')
* string/array $sqlwhere Modify conditions, allow empty, two 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=""){
//參數(shù)處理
if(is_array($table)){
$table = implode(', ', $table);
}
if(is_array($set)){
$set = implode(', ', $set);
}
if(is_array($sqlwhere)){
$sqlwhere = ' and '.implode(' and ', $sqlwhere);
}
//數(shù)據(jù)庫操作
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 enable debugging, if it is enabled, the sql statement will be output
* 0 Disable
* 1 Enable
* 2 Enable and terminate the program
* int $ mode return type
* 0 no return information
* 1 return number of execution entries
* string $table database table
* string/array $sqlwhere deletion condition, empty allowed, 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=""){
//參數(shù)處理
if(is_array($sqlwhere)){
$sqlwhere = ' and '.implode(' and ', $sqlwhere);
}
//數(shù)據(jù)庫操作
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;
}
}
}
}
其實使用上,和之前的相差不大,目的就是為了方便移植。
本次重寫著重處理了幾個問題:
?、?insert語句太復(fù)雜,fields與values對應(yīng)容易出現(xiàn)誤差
我們看下最常見的一句sql插入語句
在傳統(tǒng)模式下,fields和values參數(shù)是分開傳入的,但卻要保證兩者參數(shù)傳入的順序一致。這很容易導(dǎo)致順序錯亂或者漏傳某個參數(shù)。
這次已經(jīng)把問題修改了,采用了mysql獨有的insert語法,同樣是上面那功能,就可以換成這樣的寫法
就像update一樣,一目了然。
?、?部分參數(shù)可以用數(shù)組代替
比如這樣一句sql
在原先調(diào)用方法的時候,需要手動拼裝好where條件,這樣操作的成本很高,現(xiàn)在完全可以用這種形式
$where = array(
'tbid = 1',
'username = "hooray"'
);
$db->delete(1, 0, 'tb_member', $where);
No matter how many conditions you have, it will not disrupt your thinking. Similarly, not only the where parameter, the set in update can also be in this form (see the complete source code for details)
$set = array('username = "123"', 'type = 1', 'lastlogindt = now()');
$where = array('tbid = 1 ');
$db->update(1, 0, 'tb_member', $set, $where);
?、?Customizable sql statement
Yes Sometimes, sql is too complex, making it impossible to use the methods provided in the class to assemble sql statements. At this time, a function is needed, which is to directly pass in the sql statement I have assembled to execute and return information. Now, this function is also available
$db->query('select username, password from tb_member');
$rs = $db->fetchAll();
Is it very similar to the original writing method of pdo?
?、?Support the creation of multiple database connections
The original method does not support multiple database connections because it is just a database operation method. In implementation, you need to copy 2 identical files and modify some variables. The operation is really complicated. This problem is now solved.
$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, 2 database connections can be created at the same time for easy processing Database-to-database interaction.
There are roughly so many new features. The entire code is not much. Welcome to read and understand. The following is the test code I wrote when writing, and it is also provided for everyone to learn.
require_once('global.php');
require_once(' inc/setting.inc.php');
$db = new HRDB($db_hoorayos_config);
echo '
select test< ;hr>';
echo 'Normal mode, pass the string directly in
';
$rs = $db->select(1, 0, 'tb_member', 'username, password' , 'and type = 1 and username like "%os%"');
echo '
Array mode, you can pass 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 transfer Enter
';
$db->insert(1, 0, 'tb_member', 'username = "test", type = 1, lastlogindt = now()');
echo '< ;br>Array mode, you can pass in an array
';
$set = array('username = "test"', 'type = 1', 'lastlogindt = now()');
$db->insert(1, 0, 'tb_member', $set);
echo '
update test
';
echo 'Normal mode, pass the string directly
';
$db->update(1, 0, 'tb_member', 'username = "123", type = 1, lastlogindt = now( )', 'and tbid = 7');
echo '
Array mode, you can pass 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, pass the string directly in
';
$db->delete(1, 0, 'tb_member', 'and tbid = 1 and username = "hooray"');
echo '
Array mode, you can pass 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 Yirui

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

Execution of SELECT queries using PHP's preprocessing statements can effectively prevent SQL injection and improve security. 1. Preprocessing statements separate SQL structure from data, send templates first and then pass parameters to avoid malicious input tampering with SQL logic; 2. PDO and MySQLi extensions commonly used in PHP realize preprocessing, among which PDO supports multiple databases and unified syntax, suitable for newbies or projects that require portability; 3. MySQLi is specially designed for MySQL, with better performance but less flexibility; 4. When using it, you should select appropriate placeholders (such as? or named placeholders) and bind parameters through execute() to avoid manually splicing SQL; 5. Pay attention to processing errors and empty results to ensure the robustness of the code; 6. Close it in time after the query is completed.

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana
