Noob PHP Question

Discussion in 'PHP' started by ezyweb, Oct 14, 2009.

  1. #1
    Im writing a very basic script which takes input from a form puts it into a database.

    My question is:

    I have created a field in the db called "id" which is auto increment. After creating a new record, how do I figure out what the "id" was of the newly created record so I can put it into a variable?
     
    ezyweb, Oct 14, 2009 IP
  2. shreya_net

    shreya_net Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Hi,
    Not sure if this could help - but after you add a record, you may do a query to give you id from the last record in your database. That way you can get the id and than store it in your variable!

    Hope this helps you!
     
    shreya_net, Oct 14, 2009 IP
  3. organicCyborg

    organicCyborg Peon

    Messages:
    330
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    After you insert data into the database.

    
    // mysql_query("INSERT INTO .... ");
    
    $lastId = mysql_insert_id();
    echo "Last id to be inserted: " . $lastId;
    
    Code (markup):
     
    organicCyborg, Oct 14, 2009 IP
  4. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #4
    The practice that I follow generally in scenarios where concurrent inserts are happening is to generate a unique field for each entry and then query using that unique field.

    This mainly helps where a thread has to wait due to lock acquired by another thread or due to any other reason for a matter.
     
    mastermunj, Oct 16, 2009 IP
  5. orionoreo

    orionoreo Peon

    Messages:
    145
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I'd go with this too... the other method has room for failure or mistakes
     
    orionoreo, Oct 16, 2009 IP