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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀