PHP / MySQL关键部分

我正在使用
PHP与PDO和InnoDB表.

我只希望代码允许一个用户提交的操作完成,用户可以取消或完成.但是在用户发布这两个操作的情况下,我希望其中一个请求失败并回滚,这是当前没有发生的,两者都是完成而没有异常/错误.我认为在检查它之后删除该行就足够了.

$pdo = new PDO();

try {

    $pdo->beginTransaction();

    $rowCheck = $pdo->query("SELECT * FROM table WHERE id=99")->rowCount();

    if ($rowCheck == 0)
        throw new RuntimeException("Row isn't there");

    $pdo->exec("DELETE FROM table WHERE id = 99");

    // either cancel, which does one bunch of queries. if (isset($_POST['cancel'])) ...
    // or complete, which does another bunch of queries. if (isset($_POST['complete'])) ...
    // do a bunch of queries on other tables here...

    $pdo->commit();

} catch (Exception $e) {

    $pdo->rollback();

    throw $e;

}

如何将取消/完成操作作为关键部分?第二次操作必须失败.

最佳答案 代码很好,但有一个例外:将FOR UPDATE添加到初始SELECT.这应该足以阻止第二个按钮按下直到第一个DELETE发生,从而导致第二个按钮“失败”.

https://dev.mysql.com/doc/refman/5.5/en/innodb-locking-reads.html

Note Locking of rows for update using SELECT FOR UPDATE only applies
when autocommit is disabled (either by beginning transaction with
START TRANSACTION or by setting autocommit to 0. If autocommit is
enabled, the rows matching the specification are not locked.

点赞