dtxb75622 2014-11-27 14:56
浏览 75
已采纳

如何在PHP中管理嵌套数据库事务?

I have a method deleteUser(..) that executes a mysql query and calls another method logAction(..) that calls another mysql query.

What is the best way to handle transactions inside such methods?

Example pseudo code:

function deleteUser($userId) {
    $db->execute('BEGIN TRANSACTION');

    $userCount = $db->execute("DELETE FROM users WHERE id=$userId");

    logAction('USER DELETED');

    $db->execute('INSERT INTO ... another action');

    $db->execute('COMMIT');
}

function logAction($action) {
    $db->execute('BEGIN TRANSACTION');

    $db->execute('INSERT INTO logtable ... ACTION');
    if (error) { 
        $db->execute('ROLLBACK');
    }

    $db->execute('COMMIT');
}

As you can see, I'm calling logAction from deleteUser() method, and encountered 'BEGIN TRANSACTION' twice. Method logAction() calls 'COMMIT' prematurely before deleteUser() is done.

Is there a way to manage transactions inside such nested methods?

  • 写回答

1条回答 默认 最新

  • dpo15099 2014-11-30 09:39
    关注

    MySql does not supprot nesting transaction. Also

    Beginning a transaction causes any pending transaction to be committed

    http://dev.mysql.com/doc/refman/5.5/en/commit.html

    But you need to execute those queries inside one transaction or execute them separately. You insist to run your methods inside transaction.

    function deleteUser($userId) {
        if ($this->notInTransation()) throw new NotInTransactionException('not in transaction');
    
        $userCount = $db->execute("DELETE FROM users WHERE id=$userId");
    
        logAction('USER DELETED');
    
        $db->execute('INSERT INTO ... another action');
    
    }
    
    function logAction($action) {
        if ($this->notInTransation()) throw new NotInTransactionException('not in transaction');
        $db->execute('INSERT INTO logtable ... ACTION');
    }
    

    Thats would make you sure that your queries runes inside one transaction. With this approach you should put begin, rollback, commit higher in hierarchy, or put queries lower.

    P.S. You could use autocommit variable to check transaction being started.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败