這篇文章主要介紹了PHP基於pdo的資料庫操作類別,可實現基本的資料庫連線、增刪改查、關閉連線等操作,也支援針對mysql、sqlserver及oracle等資料庫的操作,需要的朋友可以參考下
本文實例講述了PHP基於pdo的資料庫操作類別。分享給大家供大家參考,具體如下:
工作中需要操作sqlserver、oracle都是使用的這個類,當時是在別人的基礎上改進了,現在分享下
<?php class Pdodb{ protected $pdo; protected $res; protected $config; /*构造函数*/ function __construct($config){ $this->Config = $config; $this->connect(); } /*数据库连接*/ public function connect(){ try { $this->pdo= new PDO($this->Config['dsn'], $this->Config['username'], $this->Config['password']);//$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); $this->pdo->query("set names utf8"); }catch(Exception $e){ echo '数据库连接失败,详情: ' . $e->getMessage () . ' 请在配置文件中数据库连接信息'; exit (); } /* if($this->Config['type']=='oracle'){ $this->pdo->query("set names {$this->Config['charset']};"); }else{ $this->pdo->query("set names {$this->Config['charset']};"); } */ //把结果序列化成stdClass //$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); //自己写代码捕获Exception //$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);//属性名 属性值 数组以关联数组返回 } /*数据库关闭*/ public function close(){ $this->pdo = null; } //用于有记录结果返回的操作,特别是SELECT操作 public function query($sql,$return=false){ $res = $this->pdo->query($sql); if($res){ $this->res = $res; // 未返回 return $this->res; } if($return){ return $res; } } //主要是针对没有结果集合返回的操作,比如INSERT、UPDATE、DELETE等操作 public function exec($sql,$return=false){ $res = $this->pdo->exec($sql); if($res){ $this->res = $res; } if($return){//返回操作是否成功 成功返回1 失败0 return $res; } } //将$this->res以数组返回(全部返回) public function fetchAll(){ return $this->res->fetchAll(); } //将$this->res以数组返回(一条记录) public function fetch(){ return $this->res->fetch(); } //返回所有字段 public function fetchColumn(){ return $this->res->fetchColumn(); } //返回最后插入的id public function lastInsertId(){ return $this->res->lastInsertId(); } //返回最后插入的id public function lastInsertId2(){ return $this->pdo->lastInsertId(); } /** * 参数说明 * string/array $table 数据库表,两种传值模式 * 普通模式: * 'tb_member, tb_money' * 数组模式: * array('tb_member', 'tb_money') * string/array $fields 需要查询的数据库字段,允许为空,默认为查找全部,两种传值模式 * 普通模式: * 'username, password' * 数组模式: * array('username', 'password') * string/array $sqlwhere 查询条件,允许为空,两种传值模式 * 普通模式(必须加上and,$sqlwhere为空 1=1 正常查询): * 'and type = 1 and username like "%os%"' * 数组模式: * array('type = 1', 'username like "%os%"') * string $orderby 排序,默认为id倒序 *int $debug 是否开启调试,开启则输出sql语句 * 0 不开启 * 1 开启 * 2 开启并终止程序 * int $mode 返回类型 * 0 返回多条记录 * 1 返回单条记录 * 2 返回行数 */ public function select($table, $fields="*", $sqlwhere="", $orderby="", $debug=0, $mode=0){ //参数处理 if(is_array($table)){ $table = implode(', ', $table); } if(is_array($fields)){ $fields = implode(',',$fields); /* if($this->Config['type']=='oracle'){ //$fields = implode(',',$fields);//CUSTOMER_ID,FIRST_NAME,LAST_NAME,EMAIL //$fields = implode(",'UTF8','ZHS16GBK') ,convert(",$fields); //$fields="convert(".$fields.",'UTF8','ZHS16GBK')"; }else{ $fields = implode(',',$fields); } */ } if(is_array($sqlwhere)){ $sqlwhere = ' and '.implode(' and ', $sqlwhere); } //数据库操作 if($debug === 0){ if($mode === 2){ //统计 $this->query("select count(*) from $table where 1=1 $sqlwhere"); $return = $this->fetchColumn(); }else if($mode === 1){ //返回一条 $this->query("select $fields from $table where 1=1 $sqlwhere $orderby"); $return = $this->fetch(); }else{ $this->query("select $fields from $table where 1=1 $sqlwhere $orderby"); $return = $this->fetchAll();//如果 $this->res为空即sql语句错误 会提示Call to a member function fetchAll() on a non-object } return $return; }else{ if($mode === 2){ echo "select count(*) from $table where 1=1 $sqlwhere"; }else if($mode === 1){ echo "select $fields from $table where 1=1 $sqlwhere $orderby"; }else{ echo "select $fields from $table where 1=1 $sqlwhere $orderby"; } if($debug === 2){ exit; } } } /** * 参数说明 * string/array $table 数据库表,两种传值模式 * 普通模式: * 'tb_member, tb_money' * 数组模式: * array('tb_member', 'tb_money') * string/array $set 需要插入的字段及内容,两种传值模式 * 普通模式: * 'username = "test", type = 1, dt = now()' * 数组模式: * array('username = "test"', 'type = 1', 'dt = now()') * int $debug 是否开启调试,开启则输出sql语句 * 0 不开启 * 1 开启 * 2 开启并终止程序 * int $mode 返回类型 * 0 无返回信息 * 1 返回执行条目数 * 2 返回最后一次插入记录的id */ public function oic_insert($table, $set, $debug=0, $mode=0){ //参数处理 if(is_array($table)){ $table = implode(', ', $table); } if(is_array($set)){ $s='';$i=0; foreach($set as $k=>$v){ $i++; $s[$i]=$k;//,连接 $val[$i]=$v; } $sarr=implode(",",$s);//去掉最后一个, //array_pop($sarr); $set=implode("','",$val);////15221579236','张三','','2001','8','4','女','是 //$set = implode(', ', $set); } //数据库操作 if($debug === 0){ if($mode === 2){ $this->query("insert into $table ($sarr) values('".$set."')"); //$return = $this->lastInsertId(); }else if($mode === 1){ $this->exec("insert into $table ($sarr) values('".$set."')"); $return = $this->res; }else{ $this->query("insert into $table ($sarr) values('".$set."')"); $return = NULL; } return $return; }else{ echo "insert into $table ($sarr) values('".$set."')"; if($debug === 2){ exit; } } } public function insert($table, $set, $debug=0, $mode=0){ //参数处理 if(is_array($table)){ $table = implode(', ', $table); } if(is_array($set)){ $s=''; foreach($set as $k=>$v){ $s.=$k."='".$v."',";//,连接 } $sarr=explode(',',$s);//去掉最后一个, array_pop($sarr); $set=implode(',',$sarr); //$set = implode(', ', $set); } //数据库操作 if($debug === 0){ if($mode === 2){ $this->query("insert into $table set $set"); $return = $this->pdo->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; } } } /** * 参数说明 * string $table 数据库表,两种传值模式 * 普通模式: * 'tb_member, tb_money' * 数组模式: * array('tb_member', 'tb_money') * string/array $set 需要更新的字段及内容,两种传值模式 * 普通模式: * 'username = "test", type = 1, dt = now()' * 数组模式: * array('username = "test"', 'type = 1', 'dt = now()') * string/array $sqlwhere 修改条件,允许为空,两种传值模式 * 普通模式: * 'and type = 1 and username like "%os%"' * 数组模式: * array('type = 1', 'username like "%os%"') * int $debug 是否开启调试,开启则输出sql语句 * 0 不开启 * 1 开启 * 2 开启并终止程序 * int $mode 返回类型 * 0 无返回信息 * 1 返回执行条目数 */ public function update($table, $set, $sqlwhere="", $debug=0, $mode=0){ //参数处理 if(is_array($table)){ $table = implode(', ', $table); } if(is_array($set)){ $s=''; foreach($set as $k=>$v){ $s.=$k."='".$v."',"; } $sarr=explode(',',$s);//去掉最后一个, array_pop($sarr); $set=implode(',',$sarr); //$set = implode(', ', $set); } if(is_array($sqlwhere)){ $sqlwhere = ' and '.implode(' and ', $sqlwhere); } //数据库操作 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 = true; } return $return; }else{ echo "update $table set $set where 1=1 $sqlwhere"; if($debug === 2){ exit; } } } /** * 参数说明 * string $table 数据库表 * string/array $sqlwhere 删除条件,允许为空,两种传值模式 * 普通模式: * 'and type = 1 and username like "%os%"' * 数组模式: * array('type = 1', 'username like "%os%"') * int $debug 是否开启调试,开启则输出sql语句 * 0 不开启 * 1 开启 * 2 开启并终止程序 * int $mode 返回类型 * 0 无返回信息 * 1 返回执行条目数 */ public function delete($table, $sqlwhere="", $debug=0, $mode=0){ //参数处理 if(is_array($sqlwhere)){ $sqlwhere = ' and '.implode(' and ', $sqlwhere); //是字符串需自己加上and } //数据库操作 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; } } } } /* sqlserver 配置 extension=php_pdo_mssql.dll和extension=php_pdo_sqlsrv.dll 安装对应的 ntwdblib.dll http://msdn.microsoft.com/en-us/library/cc296170.aspx 下载php版本对应的sqlsrv扩展 sqlserver 配置 odbc连接需开启extension=php_pdo_odbc.dll */ $mssql2008_config=array( 'dsn'=>'odbc:Driver={SQL Server};Server=192.168.1.60;Database=his',//数据库服务器地址 'username'=>'sa', 'password'=>'xxxxx', ); $mssql=new Pdodb($mssql2008_config); $sql="select * from ( select row_number()over(order by tempcolumn)temprownumber,* from ( select top 10 tempcolumn=0,a.* from DA_GR_HBFS a where 1=1 ) t ) tt where temprownumber>0"; $mssql->query($sql); while($res=$mssql->fetch()){ $data[]=$res; } print_r($data);exit; //mysql 操作 $msyql_config=array( 'dsn'=>'mysql:host=localhost;dbname=talk', 'username'=>'root', 'password'=>'123456' ); $mysql=new PDO_DB($msyql_config); $sql = 'SELECT user_id, user_name, nickname FROM et_users '; $mysql->query($sql); $data=$mysql->fetchAll(); print_r($data);exit; //oracle 操作 $oci_config=array( 'dsn'=>'oci:dbname=orcl', 'username'=>'BAOCRM', 'password'=>'BAOCRM' ); $oracle=new PDO_DB($oci_config); //print_r($oracle);exit;//PDO_DB Object ( [pdo:protected] => PDO Object ( ) [res:protected] => [config:protected] => [Config] => Array ( [dsn] => oci:dbname=orcl [name] => PWACRM [password] => PWACRM ) ) $sql="select * from CUSTOMER_LEVEL t"; $oracle->query($sql); $data=$oracle->fetchAll(); print_r($data);exit; /* Array ( [0] => Array ( [LEVEL_ID] => 1 [0] => 1 [LEVEL_NAME] => 普通会员 [1] => 普通会员 [LEVEL_DETAIL] => 普通会员 [2] => 普通会员 [SORT_NUMBER] => 15 [3] => 15 [CREATE_TIME] => 12-7月 -12 [4] => 12-7月 -12 [CREATE_BY] => 1 [5] => 1 [UPDATE_TIME] => 12-7月 -12 [6] => 12-7月 -12 [UPDATE_BY] => 1 [7] => 1 [STATE] => 正常 [8] => 正常 ) )*/ ?>
相關推薦:
以上是PHP基於pdo的資料庫操作類別【可支援mysql、sqlserver及oracle】的詳細內容。更多資訊請關注PHP中文網其他相關文章!

PHP用於構建動態網站,其核心功能包括:1.生成動態內容,通過與數據庫對接實時生成網頁;2.處理用戶交互和表單提交,驗證輸入並響應操作;3.管理會話和用戶認證,提供個性化體驗;4.優化性能和遵循最佳實踐,提升網站效率和安全性。

PHP在數據庫操作和服務器端邏輯處理中使用MySQLi和PDO擴展進行數據庫交互,並通過會話管理等功能處理服務器端邏輯。 1)使用MySQLi或PDO連接數據庫,執行SQL查詢。 2)通過會話管理等功能處理HTTP請求和用戶狀態。 3)使用事務確保數據庫操作的原子性。 4)防止SQL注入,使用異常處理和關閉連接來調試。 5)通過索引和緩存優化性能,編寫可讀性高的代碼並進行錯誤處理。

在PHP中使用預處理語句和PDO可以有效防範SQL注入攻擊。 1)使用PDO連接數據庫並設置錯誤模式。 2)通過prepare方法創建預處理語句,使用佔位符和execute方法傳遞數據。 3)處理查詢結果並確保代碼的安全性和性能。

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP可以輕鬆創建互動網頁內容。 1)通過嵌入HTML動態生成內容,根據用戶輸入或數據庫數據實時展示。 2)處理表單提交並生成動態輸出,確保使用htmlspecialchars防XSS。 3)結合MySQL創建用戶註冊系統,使用password_hash和預處理語句增強安全性。掌握這些技巧將提升Web開發效率。

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

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

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能