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. :-)
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.
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.
This is a property of the statement handle. You should be able to access the ID like that:
$sth->{mysql_insertid}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With