PHP/MySQL Critical section

℡╲_俬逩灬. 提交于 2020-12-31 04:52:35

问题


I'm using PHP with PDO and InnoDB tables.

I only want the code to allow one user-submitted operation to complete, the user can either cancel or complete. But in the case that the user posts both operations, I want one of the requests to fail and rollback, which isn't happening right now, both are completing without exception/error. I thought deleting the row after checking it exists would be enough.

$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;

}

How can I make the cancel / complete operations a critical section? The second operation MUST fail.


回答1:


The code is fine, with one exception: Add FOR UPDATE to the initial SELECT. That should suffice to block the second button press until the first DELETE has happened, thereby leading to the second one "failing".

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.




回答2:


Another solution just for completeness:

private function getLock() {
    $lock = $this->pdo->query("SELECT GET_LOCK('my_lock_name', 5)")->fetchColumn();

    if ($lock != "1")
        throw new RuntimeException("Lock was not gained: " . $lock);
}

private function releaseLock() {
    $releaseLock = $this->pdo->query("SELECT RELEASE_LOCK('my_lock_name')")->fetchColumn();

    if ($releaseLock != "1")
        throw new RuntimeException("Lock not properly released " . $releaseLock);
}

MySQL GET_LOCK() documentation



来源:https://stackoverflow.com/questions/30226922/php-mysql-critical-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!