程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> 一個基於PDO的數據庫操作類

一個基於PDO的數據庫操作類

編輯:PHP綜合
百度之後決定使用PDO,至於為什麼選擇PDO,這裡就不再多說,大家自己去百度下就能明白。
既然要換,那最基本就需要有個常用的數據庫操作類,也就是所謂的增刪改查等,昨晚搗騰了一晚,大致弄出了個雛形,以下就是代碼,希望大家能給出點意見。
復制代碼 代碼如下:
<?php
/*
作者:胡睿
日期:2011/03/19
電郵:[email protected]
20110319
常用數據庫操作,如:增刪改查,獲取單條記錄、多條記錄,返回最新一條插入記錄id,返回操作記錄行數等
*/
/*
參數說明
int $debug 是否開啟調試,開啟則輸出sql語句
int $getcount 是否記數,返回值為行數
int $getrow 是否返回值單條記錄
string $table 數據庫表
string $fields 需要查詢的數據庫字段,允許為空,默認為查找全部
string $sqlwhere 查詢條件,允許為空
string $orderby 排序,允許為空,默認為id倒序
*/
function hrSelect($debug, $getcount, $getrow, $table, $fields="*", $sqlwhere="", $orderby="id desc"){
global $pdo;
if($debug){
if($getcount){
echo "select count(*) from $table where 1=1 $sqlwhere order by $orderby";
}else{
echo "select $fields from $table where 1=1 $sqlwhere order by $orderby";
}
exit;
}else{
if($getcount){
$rs = $pdo->query("select count(*) from $table where 1=1 $sqlwhere order by $orderby");
return $rs->fetchColumn();
}elseif($getrow){
$rs = $pdo->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
return $rs->fetch();
}else{
$rs = $pdo->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
return $rs->fetchAll();
}
}
}
/*
參數說明
int $debug 是否開啟調試,開啟則輸出sql語句
int $execrow 是否開啟返回執行條目數
int $lastinsertid 是否開啟返回最後一條插入記錄id
string $table 數據庫表
string $fields 需要插入數據庫的字段
string $values 需要插入數據庫的信息,必須與$fields一一對應
*/
function hrInsert($debug, $execrow, $lastinsertid, $table, $fields, $values){
global $pdo;
if($debug){
echo "insert into $table ($fields) values ($values)";
exit;
}elseif($execrow){
return $pdo->exec("insert into $table ($fields) values ($values)");
}elseif($lastinsertid){
return $pdo->lastInsertId("insert into $table ($fields) values ($values)");
}else{
$pdo->query("insert into $table ($fields) values ($values)");
}
}
/*
參數說明
int $debug 是否開啟調試,開啟則輸出sql語句
int $execrow 是否開啟執行並返回條目數
string $table 數據庫表
string $set 需要更新的字段及內容,格式:a='abc',b=2,c='2010-10-10 10:10:10'
string $sqlwhere 修改條件,允許為空
*/
function hrUpdate($debug, $execrow, $table, $set, $sqlwhere=""){
global $pdo;
if($debug){
echo "update $table set $set where 1=1 $sqlwhere";
exit;
}elseif($execrow){
return $pdo->exec("update $table set $set where 1=1 $sqlwhere");
}else{
$pdo->query("update $table set $set where 1=1 $sqlwhere");
}
}
/*
參數說明
int $debug 是否開啟調試,開啟則輸出sql語句
int $execrow 是否開啟返回執行條目數
string $table 數據庫表
string $sqlwhere 刪除條件,允許為空
*/
function hrDelete($debug, $execrow, $table, $sqlwhere=""){
global $pdo;
if($debug){
echo "delete from $table where 1=1 $sqlwhere";
exit;
}elseif($execrow){
return $pdo->exec("delete from $table where 1=1 $sqlwhere");
}else{
$pdo->query("delete from $table where 1=1 $sqlwhere");
}
}
?>

參數的注釋都寫的很清楚,如果有人需要,不清楚使用方法可以直接問我。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved