Wednesday, 6 May 2009

MySQL - Last INSERT id

If you want to know which is the ID of the last INSERT been made from the current connection, when auto_increment is active, use this:

SELECT LAST_INSERT_ID();


A few lines in non-optimized perl:

my $sel_last = "SELECT LAST_INSERT_ID();";
my $sth = $dbh->prepare($sel_last)
or die "Couldn't prepare statement: " . $dbh->errstr;

$sth->execute()
or die "Couldn't execute statement: " . $sth->errstr;

my @data;
while (@data = $sth->fetchrow_array())
{
print "Last ID was.... $data[0]";
}

More details here for the MySQL statement and here for the perl DBI.

No comments:

Post a Comment