If I begin a transaction, and make multiple INSERT
s in it (pre-COMMIT
), mysql_insert_id()
doesn't seem to update following each one.
Is this the expected behavior? If so, what can I do to get the ID's for the things I just inserted?
Your assumption is wrong. Here is code that proves it:
mysql_query('CREATE TABLE `test` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB') or die(mysql_error());
mysql_query('SET AUTOCOMMIT=0') or die(mysql_error());
mysql_query('START TRANSACTION') or die(mysql_error());
mysql_query("INSERT INTO test VALUES (NULL, 'Martin')") or die(mysql_error());
echo mysql_insert_id().'<br />';
mysql_query("INSERT INTO test VALUES (NULL, 'Dani')") or die(mysql_error());
echo mysql_insert_id().'<br />';
mysql_query("INSERT INTO test VALUES (NULL, 'Pesho')") or die(mysql_error());
echo mysql_insert_id().'<br />';
mysql_query('COMMIT') or die(mysql_error());
mysql_query('SET AUTOCOMMIT=1') or die(mysql_error());
The output of this simple code is:
1
2
3
The interesting thing is that even if you rollback the transaction (instead of committing it), the result will be the same and the values for these ids will never be used again. So the next insert will start with 4.
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