Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

pdo

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;}
like image 331
user782104 Avatar asked Dec 21 '22 01:12

user782104


2 Answers

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.

like image 188
thetaiko Avatar answered Dec 23 '22 13:12

thetaiko


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);
like image 43
FtDRbwLXw6 Avatar answered Dec 23 '22 14:12

FtDRbwLXw6