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;}
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With