SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: Get an id *immediately* after creating record?

  1. #1
    Posts rarely lloydi's Avatar
    Join Date
    Jan 2002
    Location
    Swindon UK
    Posts
    617
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get an id *immediately* after creating record?

    Not sure of the best way to describe this, but I know what I'm after:

    I've just created a record and it has a primary key - set to auto-increment.

    Immediately after creating that record I need to make use of that id - which of course did not exist moments earlier - to insert a record into another table.

    How can I get the result of the first query's addition to grab that id for use in the second update/insertion? Without having to do some barmy lookup against some other parameter (or a selection of them) that I think are unique enough to give me that newly created record's id?

    Hope this makes sense!
    Build Your Own Web Site the Right Way!
    A beginners' HTML/CSS book with web standards at its heart
    The Ultimate HTML Reference
    A complete reference, in glorious hardback

  2. #2
    SitePoint Enthusiast hostentic's Avatar
    Join Date
    Oct 2010
    Location
    USA
    Posts
    30
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you are using php , there is a method that retrieves the last insert record id.
    http://php.net/manual/en/function.mysql-insert-id.php

    if you are doing it in mysql :
    http://dev.mysql.com/doc/refman/5.0/...unique-id.html

  3. #3
    Posts rarely lloydi's Avatar
    Join Date
    Jan 2002
    Location
    Swindon UK
    Posts
    617
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by hostentic View Post
    If you are using php , there is a method that retrieves the last insert record id.
    http://php.net/manual/en/function.mysql-insert-id.php

    if you are doing it in mysql :
    http://dev.mysql.com/doc/refman/5.0/...unique-id.html
    Aha, thanks - I'll read through and digest

    I am using PHP, so I could use either. Is one method preferable to use than another?
    Build Your Own Web Site the Right Way!
    A beginners' HTML/CSS book with web standards at its heart
    The Ultimate HTML Reference
    A complete reference, in glorious hardback

  4. #4
    SitePoint Wizard guelphdad's Avatar
    Join Date
    Oct 2003
    Location
    St. Catharines, ON Canada
    Posts
    1,704
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use LAST_INSERT_ID directly in the MySQL query even if you are using PHP. See the PHP manual for details, there are times when using mysql_insert_id() that an incorrect value will be returned.

Bookmarks

Posting Permissions

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