这是我的脚本:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction(); // this
$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 {
$error = true;
}
$db_conn->commit(); // this
}
catch(PDOException $e){
$db_conn->rollBack();
}
首先,我不得不说,我的剧本很好。我指的是测试的结果或预期结果。只有一件事让我害怕。我读了文件,看到了这句话:
由于使用嵌套的commit()可能会过早关闭事务,因此不起作用并且很危险。
我不知道上面句子的意思是什么,只是我知道也许我不应该在beginTransaction()
和commit()
之间使用嵌套的try - catch
。我说得对吗?这样做很危险?
异常与事务没有直接关系。您可以根据需要在代码中添加任意数量的catch块。
所以您的代码是正确的,因为您已经将PDO错误报告设置为异常。