這裏是我的腳本:我可以在PDO事務中使用try catch異常嗎?
所有的$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()過早關閉事務,所以不起作用並且很危險。
我不知道什麼是句子的上面的意思,只是我的理解,也許我不應該使用嵌套try - catch
beginTransaction()
和commit()
之間。那麼我明白了嗎?這樣做很危險嗎?
該文檔在哪裏? – Phil
如果你正在使用事務,你不必刪除錯誤記錄,只是做一個回滾......而這句話是關於嵌套'beginTransaction()'/'commit()',而不是關於try/catch。 .. – n00dl3
@Phil http://php.net/manual/en/pdo.begintransaction.php – stack