问题
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