Ok, this is probably obvious to most users but this bit me today. So I thought I would share it in case someone else makes the same mistake that I did. If you need the last insert ID from MySQL in a transaction on a table then do it before you commit. See the snippet below.

The format of the code is taken directly from the DBI pod so I've not done anything original ;). However, I've had to edit it to put it in snippet form so caveat emptor.
$dbh->{AutoCommit} = 0; $dbh->{RaiseError} = 1; my $insert_ID = 0; eval { my $sql = "some insert query"; $sth ||= $dbh->prepare ($sql); $sth->execute (@params); $insert_ID = $dbh->{'mysql_insertid'}; $dbh->commit; # commit the changes if we get this far }; if ($@) { # And commit or rollback print STDERR "Transaction aborted because $@\n"; $dbh->rollback; # undo the incomplete changes }

In reply to Last insert ID with Transactions and Mysql by simon.proctor

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.