Results 1 to 3 of 3
  1. #1
    Join Date
    May 2003
    Orlando, Fl

    Unanswered: Returning Last_Inster_ID to perl Variable

    Hey all, Im new to Perl and mysql but I have a problem. I am creating an online form used to collect information from a user. All the data from the fourm is collected and perl populates the data just fine, no problems. However, I want to give the user an account number which is an auto increment value in my database. The column name is acct_id. I am trying to find out what the last auto incremet value is using LAST_INSERT_ID() but i do not know how to assign that value to variable in my perl script. I am using dbi. For example,

    $dbh->do("SET '$acctnum'=(LAST_INSERT_ID())"); or
    $dbh->do("'$acctnum'=(LAST_INSERT_ID())"); or
    $dbh->do("$acctnum=(LAST_INSERT_ID())"); or

    How do I get the value of Last_Insert_ID into a variable in perl?
    I have several books and i dont see a deffinate answer.

    Thanks in advance!

  2. #2
    Join Date
    Mar 2003
    I know nothing about mysql, but how do you normally call the function LAST_INSERT_ID()? I'm thinking, couldnt you do something like:

    $sth1 = $dbh->prepare("insert into x (x1,x2) values (?,?)");
    $sth2 = $dbh->prepare("values LAST_INSERT_ID()");
    my $n = $sth1->execute();
    if ($n > 0) {
    my $row = $sth2->fetchrow_hashref();
    my $id = $row->{1};

  3. #3
    Join Date
    Oct 2002
    Baghdad, Iraq
    You read several books and missed this? It's mentioned in the main MySQL manual in the section on DBI, and it's mentioned in the DBD::mysql man page.

    perldoc DBD::mysql
    Reread the docs to DBI while you're at it.

    The easiest way is:

    $insertid = $dbh->{'mysql_insertid'};
    This also works:

    ($insertid) = $dbh->fetchrow_array("SELECT LAST_INSERT_ID()");
    Note the parentheses around $insertid in the second code snippet. If you don't understand why those are there, you need to go over perldoc perlsyntax or you'll have all kinds of problems with list context.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts