slackah has asked for the wisdom of the Perl Monks concerning the following question:

Hey Monks,
I'm trying to do a select statement using dbi to get the last inserted id. I've tried 'select @@identity' and it doesn't seem to work and havn't been able to find anything around the net.

Was just wondering what command or what query to use to get the last inserted id. Thanks

Replies are listed 'Best First'.
Re: DBI: last insert id
by lachoy (Parson) on Apr 24, 2003 at 03:51 UTC
Re: DBI: last insert id
by dws (Chancellor) on Apr 24, 2003 at 01:04 UTC
    I'm trying to do a select statement using dbi to get the last inserted id.

    That trick tends to be very database dependent, and may be documented in the POD for the corresponding DBD. Perhaps if you would mention which database you're using, someone might know the specifics.

      Sorry i had thought that since i was using DBI that the database would not be a factor. I'm using mysql though. I've tried using the LAST_INSERT_ID() function suggested on mysql website but havn't gotten it to work.
      $sth=$dbh->prepare("UPDATE history SET history_conf = LAST_INSERT_ID() WHERE history_id = LAST_INSERT_ID()")
        Consult the DBD::mysql POD (via "perldoc DBD::mysql"). It tells of an easier way. After an insert,
        $dbh->{mysql_insertid}
        holds the most recently assigned id. Your code might then be rewritten as
        my $id = $dbh->{mysql_insertid}; $sth = $dbh->prepare(<<"SQL"); UPDATE history SET history_conf = ? WHERE history_id = ? SQL $sth->execute($id, $id);
        I'm not sure, but that may only work if you do an insert in the same session. Are you?

        In any case, that function works fine for me, but I'm using it right after I do my inserts.

Re: DBI: last insert id
by Improv (Pilgrim) on Apr 24, 2003 at 03:28 UTC
    As a completely seperate way to do this, if it's ok that any updates to a row make it considered the 'last inserted', you can add a new column to your table of type TIMESTAMP, and mysql will keep it up to date as the most recent insert or update to that row. You could then select on that, and it'd be ok if it's from a separate session. Hope this is at least interesting, and maybe helpful :)