How many rollback should I write in a transaction?

守給你的承諾、 提交于 2019-12-25 07:43:26

问题


Hare is my script:

$id    = $_GET['id'];
$value = $_GET['val'];

// database connection here

try{
    $db_conn->beginTransaction();

    $stm1 = $db_conn->prepare("UPDATE table1 SET col = 'updated' WHERE id = ?");
    $stm1->execute(array($value));
    $done = $stm->rowCount();

    if ($done){
        try {
            $stm2 = $db_conn->prepare("INSERT into table2 (col) VALUES (?)");
            $stm2->execute(array($id));

        } catch(PDOException $e){
            if ((int) $e->getCode() === 23000) {  // row is duplicate
                $stm3 = $db_conn->prepare("DELETE FROM table2 WHERE col = ?");
                $stm3->execute(array($id));

            } else {
                $db_conn->rollBack();    // is this line of code necessarily ??
            }
        }

    } else {
        $error = true;
    }

    $db_conn->commit(); 
}
catch(PDOException $e){
    $db_conn->rollBack();
}

As you see, there is multiple (nested) try - catch blocks in my script. So I want to know, does any catch block need its own rollBack() or should I just write it once for the whole of script?


EDIT: Also as a note, that DELETE statement acts as an undo. Suppose you give a vote to a post and you want to take it back. So that DELETE statement remove it if you send a vote twice.

来源:https://stackoverflow.com/questions/37640107/how-many-rollback-should-i-write-in-a-transaction

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