全新的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ù)庫字段,允許為空,默認(rèn)為查找全部,兩種傳值模式
* 普通模式:
* '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 排序,默認(rèn)為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;
}
}
}
}
其實(shí)使用上,和之前的相差不大,目的就是為了方便移植。
本次重寫著重處理了幾個(gè)問題:
① 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)致順序錯(cuò)亂或者漏傳某個(gè)參數(shù)。
這次已經(jīng)把問題修改了,采用了mysql獨(dú)有的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)用方法的時(shí)候,需要手動(dòng)拼裝好where條件,這樣操作的成本很高,現(xiàn)在完全可以用這種形式
復(fù)制代碼 代碼如下:
$where = array(
'tbid = 1',
'username = "hooray"'
);
$db->delete(1, 0, 'tb_member', $where);
條件再多也不會(huì)打亂你的思路。同樣,不僅僅是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語句
有時(shí)候,sql過于復(fù)雜,導(dǎo)致無法使用類里提供的方法去組裝sql語句,這時(shí)候就需要一個(gè)功能,就是能直接傳入我已經(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ù)庫連接
原先的因?yàn)橹皇菙?shù)據(jù)庫操作方法,所以并不支持多數(shù)據(jù)庫連接,在實(shí)現(xiàn)上需要復(fù)制出2個(gè)相同的文件,修改部分變量,操作實(shí)屬復(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);
這樣就能同時(shí)創(chuàng)建2個(gè)數(shù)據(jù)庫連接,方便處理數(shù)據(jù)庫與數(shù)據(jù)庫交互的情況。
大致新功能就是這么多了,整個(gè)代碼并不多,歡迎閱讀了解。下面是我在編寫時(shí)寫的測試代碼,也一并提供上來,方便大家學(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();
作者:胡尐睿丶

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

熱門話題

寫好代碼和註釋能提升項(xiàng)目可維護(hù)性與專業(yè)度。 1.CleanCode強(qiáng)調(diào)清晰命名、單一職責(zé)與結(jié)構(gòu)分明,便於他人理解;2.註釋應(yīng)解釋“為什麼”,而非重複代碼功能;3.PHP註釋應(yīng)涵蓋類說明、方法參數(shù)、關(guān)鍵邏輯背景;4.實(shí)踐建議包括使用有意義變量名、統(tǒng)一註釋風(fēng)格、借助工具規(guī)範(fàn)等。

在PHP中定義常量,const更適合類內(nèi)部的常量定義,define()更靈活,適合全局或動(dòng)態(tài)定義。 1.const是語言結(jié)構(gòu),定義時(shí)必須是編譯時(shí)常量表達(dá)式,適用於類中或全局命名空間;define()是函數(shù),值可以是運(yùn)行時(shí)計(jì)算的結(jié)果。 2.const受命名空間影響,而define()定義的常量默認(rèn)全局可見。 3.const結(jié)構(gòu)清晰、IDE支持好,適合面向?qū)ο笤O(shè)計(jì);define()靈活性高但維護(hù)成本可能更高。 4.define()支持運(yùn)行時(shí)條件判斷和動(dòng)態(tài)定義,const不支持。因此,類相關(guān)的常量優(yōu)先使用co

寫PHP註釋應(yīng)明確用途、邏輯與結(jié)構(gòu)。 1.每個(gè)函數(shù)和類使用DocBlock格式說明作用、參數(shù)及返回值;2.在關(guān)鍵邏輯處解釋“為什麼”而非僅“做了什麼”;3.文件頂部添加簡要說明,包括功能、依賴與使用場景;4.避免廢話型註釋,僅在復(fù)雜邏輯前添加必要說明,不記錄修改歷史。這樣做提升代碼可讀性與維護(hù)效率。

註釋應(yīng)說明“為什麼”而非“做了什麼”,如解釋業(yè)務(wù)原因而非重複代碼操作;2.在復(fù)雜邏輯前加總覽性註釋,簡要說明流程步驟,幫助建立整體印象;3.給“奇怪”代碼加註釋,解釋非常規(guī)寫法的意圖,避免誤解為bug;4.註釋格式建議簡潔為主,單行用//,函數(shù)/類用/*.../,保持統(tǒng)一風(fēng)格;5.避免註釋與代碼不同步、註釋過長或註釋掉代碼未刪除等問題,確保註釋真正提升代碼可讀性和維護(hù)性。

易於效率,啟動(dòng)啟動(dòng)tingupalocalserverenverenvirestoolslikexamppandacodeeditorlikevscode.1)installxamppforapache,mysql,andphp.2)uscodeeditorforsyntaxssupport.3)

第一步選擇集成環(huán)境包XAMPP或MAMP搭建本地服務(wù)器;第二步根據(jù)項(xiàng)目需求選擇合適的PHP版本並配置多版本切換;第三步選用VSCode或PhpStorm作為編輯器並搭配Xdebug進(jìn)行調(diào)試;此外還需安裝Composer、PHP_CodeSniffer、PHPUnit等工具輔助開發(fā)。

註釋在代碼中至關(guān)重要因?yàn)樗嵘舜a的可讀性和維護(hù)性特別是在PHP這種多協(xié)作和長期維護(hù)的項(xiàng)目中。寫註釋的原因包括解釋“為什麼這麼做”節(jié)省調(diào)試時(shí)間對新手友好減少溝通成本。好註釋的表現(xiàn)形式有說明函數(shù)或類的作用解釋複雜邏輯的意圖標(biāo)記待辦事項(xiàng)或潛在問題以及編寫API接口文檔註釋。壞註釋的典型表現(xiàn)包括重複代碼內(nèi)容註釋與代碼不一致用註釋掩蓋爛代碼以及保留陳舊信息。寫註釋的建議包括優(yōu)先註釋“為什麼”保持註釋與代碼同步使用統(tǒng)一格式避免情緒化語句並在代碼難以理解時(shí)考慮優(yōu)化代碼而非依賴註釋。

PHP比較運(yùn)算符需注意類型轉(zhuǎn)換問題。 1.使用==僅比較值,會(huì)進(jìn)行類型轉(zhuǎn)換,如1=="1"為true;2.使用===需值與類型均相同,如1==="1"為false;3.大小比較可作用於數(shù)值和字符串,如"apple"
