Friday, June 1, 2007

Finding out id of last inserted record using DBI+perl+MySQL

Countless times... and i mean COUNTLESS times i have encountered the pitfall of.... how to find out the value of the autoincrement field of an insert statement, or to put it in layman terms: How do i identify that last insert i did?

Well the answer had been smiling back at me the whole time. Those smart people who wrote the perl DBI::Mysql module had thought of that and came up with mysql_insertid function.

Let's get to it!

$sql="insert into sdata(somedata) values(\"somevalue\")";
$sth = $dbh->prepare($sql);
$sth->execute();
$id = $dbh->{ q{mysql_insertid}};
$sth->finish();


Now $id holds the value of Id (my autoincrement field in that table).

A thing of beauty!! Hope this helps! bye!