Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch the last row I inserted using DBI?

Tags:

perl

dbi

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

like image 648
Alan Haggai Alavi Avatar asked Dec 15 '09 11:12

Alan Haggai Alavi


People also ask

How do I find the last inserted record?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command.

How do I get the unique ID for the last inserted row?

9 Obtaining the Unique ID for the Last Inserted Row. If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.


2 Answers

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

$sth->{mysql_insertid} 
like image 164
innaM Avatar answered Oct 13 '22 00:10

innaM


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.

like image 24
Graham Miln Avatar answered Oct 13 '22 01:10

Graham Miln