野兔是我的剧本:
$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();
}
如您所见,我的脚本中有多个(嵌套)try - catch
块。所以我想知道,任何catch
块是否需要自己的rollBack()
,或者我应该为整个脚本编写一次?
编辑:另请注意,DELETE
语句充当撤消。假设你对一篇文章进行投票,你想要收回它。因此,如果您发送两次投票,DELETE
语句会将其删除。