35

How can I fetch the last row that was inserted using DBI (DBD::mysql)?

Code sample:

my $sth = $dbh->prepare('INSERT INTO a ( x, y, z ) VALUES ( ?, ?, ? )');
$sth->execute( $x, $y, $z );

How can I get access to the data that was inserted by the above prepare statement? I need to get the primary ID (AUTOINCREMENT) value.

UPDATE:

From DBD::mysql documentation:

An alternative way for accessing this attribute is via $dbh->{'mysql_insertid'}.

Thank you Manni and n0rd for your answers. :-)

Community
  • 1
  • 1
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127

3 Answers3

35

This is a property of the statement handle. You should be able to access the ID like that:

$sth->{mysql_insertid}
innaM
  • 47,505
  • 4
  • 67
  • 87
  • 13
    `$dbh->{mysql_insertid}` returns the same. – Eugene Yarmash Mar 29 '13 at 12:48
  • Couldn't you get a different answer, if there was an insert between your insert and this call? – Sam Selikoff Sep 09 '13 at 18:57
  • Of course. Your supposed to query `$sth->{ mysql_insertid }` immediately after the INSERT statement your interested in. – innaM Sep 10 '13 at 12:51
  • Rephrasing something that was said below. . . I believe what Sam is asking is whether the window between inserting and retrieving could have an intervening insert from an outside process. Yes it could, but the mysql_insertid (and don't try this on oracle) is the last insert that *your session* executed, so no worries there. – Vic K Nov 20 '19 at 13:58
34

A database agnostic approach is to use the DBI's last_insert_id method. This approach helps to reduce dependency on a specific database:

$dbh->last_insert_id

$rv = $dbh->last_insert_id($catalog, $schema, $table, $field);

Returns a value 'identifying' the row just inserted, if possible. Typically this would be a value assigned by the database server to a column with an auto_increment or serial type. Returns undef if the driver does not support the method or can't determine the value.

Graham Miln
  • 2,724
  • 3
  • 33
  • 33
6

SELECT LAST_INSERT_ID() query will also return what you want.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
n0rd
  • 11,850
  • 5
  • 35
  • 56