一个基于PDO的数据库操作类(新) 一个PDO事务实例

时间:2021-05-25

复制代码 代码如下:
<?php
/*
* 作者:胡睿
* 日期:2011/03/19
* 电邮:hooray0905@foxmail.com
*
* 20110319
* 常用数据库操作,如:增删改查,获取单条记录、多条记录,返回最新一条插入记录id,返回操作记录行数等
* 20110630
* 整体修改方法,合并部分参数
* 规范代码,一个方法里只有1个return语句
*/

function hrSelect($debug, $mode, $table, $fields="*", $sqlwhere="", $orderby="id desc"){
global $pdo;
if($debug){
if($mode == 2){
echo "select count(*) from $table where 1=1 $sqlwhere order by $orderby";
}elseif($mode == 1){
echo "select $fields from $table where 1=1 $sqlwhere";
}else{
echo "select $fields from $table where 1=1 $sqlwhere order by $orderby";
}
exit;
}else{
if($mode == 2){
$rs = $pdo->query("select count(*) from $table where 1=1 $sqlwhere order by $orderby");
$return = $rs->fetchColumn();
}elseif($mode == 1){
$rs = $pdo->query("select $fields from $table where 1=1 $sqlwhere");
$return = $rs->fetch();
}else{
$rs = $pdo->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
$return = $rs->fetchAll();
}
return $return;
}
}

function hrInsert($debug, $mode, $table, $fields, $values){
global $pdo;
if($debug){
echo "insert into $table ($fields) values ($values)";
exit;
}else{
if($mode == 2){
$return = $pdo->lastInsertId("insert into $table ($fields) values ($values)");
}elseif($mode == 1){
$return = $pdo->exec("insert into $table ($fields) values ($values)");
}else{
$pdo->query("insert into $table ($fields) values ($values)");
exit;
}
return $return;
}
}

function hrUpdate($debug, $mode, $table, $set, $sqlwhere=""){
global $pdo;
if($debug){
echo "update $table set $set where 1=1 $sqlwhere";
exit;
}else{
if($mode==1){
$return = $pdo->exec("update $table set $set where 1=1 $sqlwhere");
}else{
$pdo->query("update $table set $set where 1=1 $sqlwhere");
exit;
}
return $return;
}
}

function hrDelete($debug, $mode, $table, $sqlwhere=""){
global $pdo;
if($debug){
echo "delete from $table where 1=1 $sqlwhere";
exit;
}else{
if($mode == 1){
$return = $pdo->exec("delete from $table where 1=1 $sqlwhere");
}else{
$pdo->query("delete from $table where 1=1 $sqlwhere");
exit;
}
return $return;
}
}
?>

另外一段代码是基于我这个数据库操作类的事务实例:
复制代码 代码如下:

try{
$pdo->beginTransaction();
hrInsert(0,1,"class","name,parentid","'god',0"); //可以正常执行
hrInsert(0,0,0,"tb_searchlog","userid,code","4"); //出错
$pdo->commit();
}catch(Exception $e){
$pdo->rollBack();
echo "Failed: " . $e->getMessage();
}

代码下载:点击下载

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章