Uncaught exception 'PDOException' with message 'There is no active transaction'?

只谈情不闲聊 提交于 2019-12-30 09:53:19

问题


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;}

回答1:


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.

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.




回答2:


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_AUTOCOMMIT to disable this behavior:

$conn->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE);


来源:https://stackoverflow.com/questions/9418663/uncaught-exception-pdoexception-with-message-there-is-no-active-transaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!