in reply to last_insert_id did not work

Corion is right that the method should be called on $dbh (though in my test it worked on $sth too, so I'm not sure that's the problem here). Note the documentation: "The last_insert_id method was added in DBI 1.38." - what version do you have?

use warnings; use strict; use feature 'say'; use DBI; my $dbh = DBI->connect( "DBI:mysql:database=testing;host=127.0.0.1", $ENV{USER}, 'barfoo', { RaiseError => 1, AutoCommit => 1 }); $dbh->do('DROP TABLE IF EXISTS coacttran'); $dbh->do(<<'ENDSQL'); CREATE TABLE coacttran ( id INT PRIMARY KEY AUTO_INCREMENT, foo VARCHAR(256) ); ENDSQL for my $i (1..10) { my $req = qq{ INSERT INTO `coacttran` SET foo=? }; my $sth = $dbh->prepare($req); my $row = $sth->execute("bar$i"); say $dbh->last_insert_id; }

I spun up the test database with Docker the same way I showed here.

Also note that I don't know how you're generating $_pstmt, but you really should use placeholders! See Bobby Tables.

Replies are listed 'Best First'.
Re^2: last_insert_id did not work
by bizactuator (Sexton) on Mar 27, 2021 at 08:38 UTC
    I am using placeholders like this:
    $_pstmt .= ',' if $_pstmt; $_pstmt .= '`fsb_details` = ?'; push(@placeholder,"$_fsbdotnot");
    then I put $_pstmt for the places ???
    then the @placeholder for the things to put on it...

      Ok, that's good to know, and the code you've shown so far is fine, so if you're doing it that way everywhere it's good. Anytime you interpolate strings into SQL is a place for potential quoting and similar issues, which is why I made that comment. Note that there are also modules to help you generate SQL, like SQL::Abstract.