在PDO中使用事务

一般还是ORM的事务方便一些,下面是PHP原生PDO MySQL的事务。

function getPDO(){
    $dsn        = 'mysql:dbname='.config('database')['database'].';host='.config('database')['hostname'];
    $username   = config('database')['username'];
    $password   = config('database')['password'];

    try {
        $dbh = new PDO($dsn, $username, $password);
    } catch (PDOException $e) {
        // echo 'Connection failed: ' . $e->getMessage();
        return false;
    }
    return $dbh;
}


$dbh = getPDO();
try{
    $dbh->beginTransaction();

    $sth = $dbh->prepare("UPDATE tp_user SET balance = :balance WHERE id=:userid");
    $sth->execute(['balance'=>$balance, 'userid'=>$user['id']]);
    $sth = $dbh->prepare("UPDATE tp_user_charge SET status=1 WHERE id=:id");
    $sth->execute(['id'=>$id]);
    
    $dbh->commit();
    return $this->success("充值成功");
} catch(Exception $e) {
    $dbh->rollBack();
    return $this->error("充值失败:".$e->getMessage());
}

 

 

修改时间 2019-06-25

真诚赞赏,手留余香
赞赏
随机推荐
webpack报错:Cannot assign to read only property 'exports' of object
Git 重写历史,修改commit 的注释
如何选择开源许可证?
Sublime Text 3为新的扩展文件类型实现语法高亮
dedecms让channelartlist标签支持currentstyle属性方
在IIS7中使用ARR(Application Request Routing)反向代理
npx 是什么?
Windows下,Apache安全防护WAF,安装配置mod_security模块
敏捷开发笔记
PS手绘20171015