Hi I am implementing transaction using php and mysql. Below is my code where i am inserting into test in which id is an autoincrement value.
try{
$dbh->beginTransaction();
$stmt = $dbh->prepare("INSERT INTO test(id,name) VALUES (?,?)")
$stmt->execute(array(null ,$Name));
-----
----- and some more queries
$dbh-> commit();
$dbh=null;
}
catch(Exception $e)
{
$dbh->rollBack();
$dbh=null;
}
The problem i am facing is each time when transaction is rolledBack due to some exception the next time when i run the query insert is working based on the autoincrement value assigned when it was last run
for eg:
Run 1:
insert query — id value is 1 and the transaction is rolledBack
Run2:
insert query — Now it is taking id value as 2 although my previous transaction was rolledBack
Could anyone help me with this?
That happened because autoincrement value is shared among all transactins and by its nature it is DDL, not DML. Thus it cannot be rolled back (as well as any other DDL, like
TRUNCATEorALTERcannot be rolled back).PS: autoincrement PK is a surrogate key, which means that you shouldn’t care of what value it keeps. You should be satisfied with just a fact that it is unique. That’s all. If you need to maintain some “order” – create another column and do that manually.