php 未捕获的异常“PDOException”与消息“没有活动事务”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9418663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught exception 'PDOException' with message 'There is no active transaction'?
提问by user782104
This is the code i use to insert record. Whenever there is insert error , The subscriber table auto - inc number will still increase even i have roll back? What is the problem? I just want the auto increment number not add when error occur.thanks a lot for help .
这是我用来插入记录的代码。每当出现插入错误时,即使我已回滚,订阅者表自动公司编号仍会增加吗?问题是什么? 我只想在发生错误时不添加自动增量号。非常感谢您的帮助。
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);
$conn->beginTransaction();
try {
$email = $_POST['Email'];
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$query="INSERT INTO subscriber (Email,FirstName,LastName,CreateDate) VALUES (?,?,?,CURDATE())";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $email , PDO::PARAM_STR);
$stmt->bindParam(2, $FirstName, PDO::PARAM_STR);
$stmt->bindParam(3, $LastName, PDO::PARAM_STR);
$stmt->execute();
$conn->commit();
}
catch(PDOException $e)
{
$conn->rollBack();
die ($e->getMessage()."<a href='addSub.php'>Back</a>");
}
$conn->beginTransaction();
try {
$userID = $_SESSION['username'];
$query="INSERT INTO list_sub (SubID,ListID) VALUES ('',$_SESSION[ListID])";
$stmt = $conn->prepare($query);
$stmt->execute();
$conn->commit();
}
catch(PDOException $e)
{
$conn->rollBack();
die ($e->getMessage()."<a href='addSub.php'>Back</a>");
}
$conn = null;}
回答by thetaiko
Without knowing line numbers in your code, its hard to knowbut you commit your transaction at the end of the first try-catch block, and then proceed without starting a new transaction in your second try-catch block.
如果不知道代码中的行号,就很难知道,但是您在第一个 try-catch 块的末尾提交了事务,然后在第二个 try-catch 块中不启动新事务就继续进行。
Add $conn->beginTransaction();
at the beginning of your second try-catch block.
$conn->beginTransaction();
在第二个 try-catch 块的开头添加。
EDIT - You mention "I just want the auto increment number not add when error occur". You should not rely on the auto-increment feature to generate a "gapless" sequence of numbers.
编辑 - 您提到“我只想在发生错误时不添加自动增量号”。您不应依赖自动递增功能来生成“无间隙”数字序列。
回答by FtDRbwLXw6
PDO's auto-commit is probably enabled, and it's causing a problem when you try to rollback, since it has already committed. You can use PDO::ATTR_AUTOCOMMITto disable this behavior:
PDO 的自动提交可能已启用,并且在您尝试回滚时会导致问题,因为它已经提交。您可以使用PDO::ATTR_AUTOCOMMIT禁用此行为:
$conn->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);