PDO MySQL事务

  1. 作者QQ:67065435 QQ群:821635552

  2. 本站内容全部为作者原创,转载请注明出处!

  3. 示例代码

    <?php
    //ext:pdo
    //ext:pdo_mysql
    $username = "mysql";
    $password = "**************";
    $dsn = "mysql:dbname=data_base;host=127.0.0.1";
    $dbh = new PDO($dsn, $username, $password);
    if (!$dbh) {
     die('数据库连接失败');
    }
    try {
     $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
     $dbh->beginTransaction();
    
     $user_name = "test12345";
     $pass_word = "test12345";
     $nick_name = "测试用昵称";
     $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('数据库操作失败');
    }
    
Copyright © 豆包嘿嘿~ 2012-∞ 冀ICP备17033181号 all right reserved,powered by Gitbook修订: 21-07-07 12:25

results matching ""

    No results matching ""