全新的PDO數(shù)據(jù)庫操作類php版(僅適用Mysql)
Jun 13, 2016 am 11:58 AM
復(fù)制代碼 代碼如下:
/**
* 作者:胡睿
* 日期:2012/07/21
* 電郵: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();
}
/**
* 參數(shù)說明
* int $debug 是否開啟調(diào)試,開啟則輸出sql語句
* 0 不開啟
* 1 開啟
* 2 開啟并終止程序
* int $mode 返回類型
* 0 返回多條記錄
* 1 返回單條記錄
* 2 返回行數(shù)
* string/array $table 數(shù)據(jù)庫表,兩種傳值模式
* 普通模式:
* 'tb_member, tb_money'
* 數(shù)組模式:
* array('tb_member', 'tb_money')
* string/array $fields 需要查詢的數(shù)據(jù)庫字段,允許為空,默認為查找全部,兩種傳值模式
* 普通模式:
* 'username, password'
* 數(shù)組模式:
* array('username', 'password')
* string/array $sqlwhere 查詢條件,允許為空,兩種傳值模式
* 普通模式:
* 'and type = 1 and username like "%os%"'
* 數(shù)組模式:
* array('type = 1', 'username like "%os%"')
* string $orderby 排序,默認為id倒序
*/
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;
}
}
}
/**
* 參數(shù)說明
* int $debug 是否開啟調(diào)試,開啟則輸出sql語句
* 0 不開啟
* 1 開啟
* 2 開啟并終止程序
* int $mode 返回類型
* 0 無返回信息
* 1 返回執(zhí)行條目數(shù)
* 2 返回最后一次插入記錄的id
* string/array $table 數(shù)據(jù)庫表,兩種傳值模式
* 普通模式:
* 'tb_member, tb_money'
* 數(shù)組模式:
* array('tb_member', 'tb_money')
* string/array $set 需要插入的字段及內(nèi)容,兩種傳值模式
* 普通模式:
* 'username = "test", type = 1, dt = now()'
* 數(shù)組模式:
* 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;
}
}
}
/**
* 參數(shù)說明
* int $debug 是否開啟調(diào)試,開啟則輸出sql語句
* 0 不開啟
* 1 開啟
* 2 開啟并終止程序
* int $mode 返回類型
* 0 無返回信息
* 1 返回執(zhí)行條目數(shù)
* string $table 數(shù)據(jù)庫表,兩種傳值模式
* 普通模式:
* 'tb_member, tb_money'
* 數(shù)組模式:
* array('tb_member', 'tb_money')
* string/array $set 需要更新的字段及內(nèi)容,兩種傳值模式
* 普通模式:
* 'username = "test", type = 1, dt = now()'
* 數(shù)組模式:
* array('username = "test"', 'type = 1', 'dt = now()')
* string/array $sqlwhere 修改條件,允許為空,兩種傳值模式
* 普通模式:
* 'and type = 1 and username like "%os%"'
* 數(shù)組模式:
* 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;
}
}
}
/**
* 參數(shù)說明
* int $debug 是否開啟調(diào)試,開啟則輸出sql語句
* 0 不開啟
* 1 開啟
* 2 開啟并終止程序
* int $mode 返回類型
* 0 無返回信息
* 1 返回執(zhí)行條目數(shù)
* string $table 數(shù)據(jù)庫表
* string/array $sqlwhere 刪除條件,允許為空,兩種傳值模式
* 普通模式:
* 'and type = 1 and username like "%os%"'
* 數(shù)組模式:
* 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插入語句
復(fù)制代碼 代碼如下:
insert into tb_member (username, type, dt) values ('test', 1, now())
在傳統(tǒng)模式下,fields和values參數(shù)是分開傳入的,但卻要保證兩者參數(shù)傳入的順序一致。這很容易導(dǎo)致順序錯亂或者漏傳某個參數(shù)。
這次已經(jīng)把問題修改了,采用了mysql獨有的insert語法,同樣是上面那功能,就可以換成這樣的寫法
復(fù)制代碼 代碼如下:
insert into tb_member set username = "test", type = 1, lastlogindt = now()
就像update一樣,一目了然。
?、?部分參數(shù)可以用數(shù)組代替
比如這樣一句sql
復(fù)制代碼 代碼如下:
delete from tb_member where 1=1 and tbid = 1 and username = "hooray"
在原先調(diào)用方法的時候,需要手動拼裝好where條件,這樣操作的成本很高,現(xiàn)在完全可以用這種形式
復(fù)制代碼 代碼如下:
$where = array(
'tbid = 1',
'username = "hooray"'
);
$db->delete(1, 0, 'tb_member', $where);
條件再多也不會打亂你的思路。同樣,不僅僅是where參數(shù),update里的set也可以以這種形式(具體可參見完整源碼)
復(fù)制代碼 代碼如下:
$set = array('username = "123"', 'type = 1', 'lastlogindt = now()');
$where = array('tbid = 1');
$db->update(1, 0, 'tb_member', $set, $where);
③ 可自定義sql語句
有時候,sql過于復(fù)雜,導(dǎo)致無法使用類里提供的方法去組裝sql語句,這時候就需要一個功能,就是能直接傳入我已經(jīng)組裝好的sql語句執(zhí)行,并返回信息?,F(xiàn)在,這功能也有了
復(fù)制代碼 代碼如下:
$db->query('select username, password from tb_member');
$rs = $db->fetchAll();
是不是很像pdo原生態(tài)的寫法?
?、?支持創(chuàng)建多數(shù)據(jù)庫連接
原先的因為只是數(shù)據(jù)庫操作方法,所以并不支持多數(shù)據(jù)庫連接,在實現(xiàn)上需要復(fù)制出2個相同的文件,修改部分變量,操作實屬復(fù)雜?,F(xiàn)在這問題也解決了。
復(fù)制代碼 代碼如下:
$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);
這樣就能同時創(chuàng)建2個數(shù)據(jù)庫連接,方便處理數(shù)據(jù)庫與數(shù)據(jù)庫交互的情況。
大致新功能就是這么多了,整個代碼并不多,歡迎閱讀了解。下面是我在編寫時寫的測試代碼,也一并提供上來,方便大家學(xué)習(xí)。
復(fù)制代碼 代碼如下:
require_once('global.php');
require_once('inc/setting.inc.php');
$db = new HRDB($db_hoorayos_config);
echo '
select測試
';
echo '普通模式,直接字符串傳入
';
$rs = $db->select(1, 0, 'tb_member', 'username, password', 'and type = 1 and username like "%os%"');
echo '
數(shù)組模式,可傳入數(shù)組
';
$fields = array('username', 'password');
$where = array('type = 1', 'username like "%os%"');
$rs = $db->select(1, 0, 'tb_member', $fields, $where);
echo '
insert測試
';
echo '普通模式,直接字符串傳入
';
$db->insert(1, 0, 'tb_member', 'username = "test", type = 1, lastlogindt = now()');
echo '
數(shù)組模式,可傳入數(shù)組
';
$set = array('username = "test"', 'type = 1', 'lastlogindt = now()');
$db->insert(1, 0, 'tb_member', $set);
echo '
update測試
';
echo '普通模式,直接字符串傳入
';
$db->update(1, 0, 'tb_member', 'username = "123", type = 1, lastlogindt = now()', 'and tbid = 7');
echo '
數(shù)組模式,可傳入數(shù)組
';
$set = array('username = "123"', 'type = 1', 'lastlogindt = now()');
$where = array('tbid = 1');
$db->update(1, 0, 'tb_member', $set, $where);
echo '
delete測試
';
echo '普通模式,直接字符串傳入
';
$db->delete(1, 0, 'tb_member', 'and tbid = 1 and username = "hooray"');
echo '
數(shù)組模式,可傳入數(shù)組
';
$where = array(
'tbid = 1',
'username = "hooray"'
);
$db->delete(1, 0, 'tb_member', $where);
echo '
自定義sql
';
$db->query('select username, password from tb_member');
$rs = $db->fetchAll();
var_dump($rs);
$db->close();
作者:胡尐睿丶

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

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

Turn on MySQL slow query logs and analyze locationable performance issues. 1. Edit the configuration file or dynamically set slow_query_log and long_query_time; 2. The log contains key fields such as Query_time, Lock_time, Rows_examined to assist in judging efficiency bottlenecks; 3. Use mysqldumpslow or pt-query-digest tools to efficiently analyze logs; 4. Optimization suggestions include adding indexes, avoiding SELECT*, splitting complex queries, etc. For example, adding an index to user_id can significantly reduce the number of scanned rows and improve query efficiency.

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

MySQL paging is commonly implemented using LIMIT and OFFSET, but its performance is poor under large data volume. 1. LIMIT controls the number of each page, OFFSET controls the starting position, and the syntax is LIMITNOFFSETM; 2. Performance problems are caused by excessive records and discarding OFFSET scans, resulting in low efficiency; 3. Optimization suggestions include using cursor paging, index acceleration, and lazy loading; 4. Cursor paging locates the starting point of the next page through the unique value of the last record of the previous page, avoiding OFFSET, which is suitable for "next page" operation, and is not suitable for random jumps.

TosecurelyconnecttoaremoteMySQLserver,useSSHtunneling,configureMySQLforremoteaccess,setfirewallrules,andconsiderSSLencryption.First,establishanSSHtunnelwithssh-L3307:localhost:3306user@remote-server-Nandconnectviamysql-h127.0.0.1-P3307.Second,editMyS

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

MySQL transactions and lock mechanisms are key to concurrent control and performance tuning. 1. When using transactions, be sure to explicitly turn on and keep the transactions short to avoid resource occupation and undolog bloating due to long transactions; 2. Locking operations include shared locks and exclusive locks, SELECT...FORUPDATE plus X locks, SELECT...LOCKINSHAREMODE plus S locks, write operations automatically locks, and indexes should be used to reduce the lock granularity; 3. The isolation level is repetitively readable by default, suitable for most scenarios, and modifications should be cautious; 4. Deadlock inspection can analyze the details of the latest deadlock through the SHOWENGINEINNODBSTATUS command, and the optimization methods include unified execution order, increase indexes, and introduce queue systems.
