www.webdeveloper.com
Results 1 to 3 of 3

Thread: is PDO::lastInsertId reliable

  1. #1
    Join Date
    Mar 2011
    Posts
    103

    is PDO::lastInsertId reliable

    Hi. I've got a mysql table with a field that is auto-incremented on insert. Sometimes, I need to grab the auto-incremented value of that field right after I do an insert.

    I'm using PDO, and lastInsertId seems to fit the bill, but I've read some stuff that suggests that we shouldn't rely on the value returned to be correct. Why not? Is there a reliable way to fetch the auto-incremented value from the record I just inserted?

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,157
    I think it depends on what DBMS you are actually using. For instance, with PostgreSQL, it will not work (or possibly will with the optional 2nd parameter specifying the sequence object?). Fortunately, PostgreSQL allows you to return it as part of the insert query itself by using its RETURNING syntax (which is what we do where I work). If you're using MySQL, you should be okay, as it will presumably be calling MySQL's LAST_INSERT_ID() function.

    This only really becomes an issue if/when you want to change the underlying DBMS or are developing an app that you want to be able to use with multiple DB drivers. In that case, you might need to set up some switches or child classes to deal with different DB drivers.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Mar 2011
    Posts
    103
    NogDog, You're the best. Thanks a whole bunch.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles