How can I fetch the last row I inserted using DBI?
Asked Answered
J

3

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. :-)

Jell answered 15/12, 2009 at 11:45 Comment(0)
T
35

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

$sth->{mysql_insertid}
Tiernan answered 15/12, 2009 at 11:48 Comment(4)
$dbh->{mysql_insertid} returns the same.Gillum
Couldn't you get a different answer, if there was an insert between your insert and this call?Straitjacket
Of course. Your supposed to query $sth->{ mysql_insertid } immediately after the INSERT statement your interested in.Tiernan
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.Timber
H
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.

Hampstead answered 23/9, 2014 at 14:4 Comment(1)
Some DBD drivers work with just $dbh->last_insert_id() (e.g., DBD::MariaDB).Pons
R
6

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

Richthofen answered 15/12, 2009 at 11:51 Comment(2)
@Anthony that is incorrect. LAST_INSERT_ID() is related only to your current mysql connection and is unaffected by what anybody else are doing on your server.Commoner
Underlying DBI driver maybe not mysqlAdmetus

© 2022 - 2024 — McMap. All rights reserved.