PDO MySQL事务

  1. PHP中使用事务的实例

     <?php
     $dsn = "mysql:dbname=test;host=127.0.0.1";
     $username = "mysql";
     $password = "**************";
     $dbh = new PDO($dsn, $username, $password);
     if (!$dbh) {
         die('数据库连接失败');
     } else {
         $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     }
     try {
         $dbh->beginTransaction();
    
         $user_name = "test01";
         $pass_word = "**************";
         $nick_name = "测试账号01";
         $sql1 = "INSERT INTO `user`(user_name, pass_word, nick_name)VALUES(:user_name, :pass_word, :nick_name)";
         $sth = $dbh->prepare($sql1);
         $sth->bindParam('user_name', $user_name);
         $sth->bindParam('pass_word', $pass_word);
         $sth->bindParam('nick_name', $nick_name);
         $sth->execute();
         $user_id = $dbh->lastInsertId();
         unset($sth);
    
         $user_coin = 0;
         $insert_time = time();
         $sql2 = "INSERT INTO `user_coin`(user_id, user_coin, insert_time)VALUES(:user_id, :user_coin, :insert_time)";
         $sth = $dbh->prepare($sql2);
         $sth->bindParam('user_id', $user_id);
         $sth->bindParam('user_coin', $user_coin);
         $sth->bindParam('insert_time', $insert_time);
         $sth->execute();
         unset($sth);
    
         $dbh->commit();
         die('数据库操作成功');
     } catch (PDOException $e) {
         $dbh->rollback();
         die('数据库操作失败');
     }
    
@耿志环 2012-∞ 冀ICP备17033181号, powered by Gitbook修订: 2019-07-08 16:49:59

results matching ""

    No results matching ""