Insert data into DB, return ID number

Discussion in 'Databases' started by tlshaheen, Mar 9, 2010.

  1. #1
    I'm inserting an Article into a DB. The fields I'm inserting are Title, Intro, Content, Creation_Date. There is a field in the DB that is the primary key, Article_ID, which is auto-increment.

    I insert the article into the DB, and it is assigned the article_id by the DB. I want to use that ID later in my code on the same page. Is there any way to get SQL to return the ID on my Insert statement, or must I do a SELECT ... WHERE statement after I do my insert?
     
    tlshaheen, Mar 9, 2010 IP
  2. tlshaheen

    tlshaheen Peon

    Messages:
    89
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Found my solution r posterthanks to anothe: There's a MySQL function called LAST_INSERT_ID()
    There is also a PHP function called mysql_insert_id()
     
    tlshaheen, Mar 9, 2010 IP
  3. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #3
    Do not completely rely on LAST_INSERT_ID() or mysql_insert_id(), they might return wrong values in case of concurrent inserts.

    Instead have a column where you can insert a unique key for each entry and then query using that key to retrieve the id. if you can keep unique key to be numeric bigint, you can avoid having auto_increment key as well.
     
    mastermunj, Mar 10, 2010 IP