问题描述
这是我用来插入记录的代码.每当出现插入错误时,即使我已经回滚,订户表的自动编号仍会增加?问题是什么? 我只希望错误发生时不添加自动递增编号.非常感谢您的帮助.
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;}
推荐答案
在代码中不知道行号的情况下,很难知道,但是您在第一次try-catch的结尾提交了事务块,然后在第二个try-catch块中继续进行而不启动新事务.
Without knowing line numbers in your code, its hard to know but 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块的开头添加$conn->beginTransaction();
.
Add $conn->beginTransaction();
at the beginning of your second try-catch block.
编辑-您提到我只希望错误发生时不添加自动递增编号".您不应依靠自动递增功能来生成无间隙"的数字序列.
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.
这篇关于消息为“没有活动交易"的未捕获异常"PDOException"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!