PDO的数据库操作类
-
-
-
-
-
-
-
-
-
-
-
- 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;
- }
- }
另外一段代码是基于我这个数据库操作类的事务实例,注意,数据库操作表类型必须为InnoDB,其他类型不支持事务.
PDO事务机制:
$pdo->beginTransaction(); --开启事务
$pdo->commit(); --结束事务
$pdo->rollBack(); --回滚操作
示例,用try/catch包住db操作,当事务内的db操作出现中断,则执行回滚并抛出异常信息,代码如下:
- 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();
- }