dbTalk Databases Forums  

retrieving new record ID?

mailing.database.mysql mailing.database.mysql


Discuss retrieving new record ID? in the mailing.database.mysql forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Ravenslay3r
 
Posts: n/a

Default retrieving new record ID? - 07-18-2004 , 01:50 PM






I'm making a web-site thats backended by php-2-mysql. A common problem seems
to be when processing form data, I use information early in the form to
create a new record in a main table. I then immediately need the
auto_incremented Key-ID of the new record to put other information in
related tables.

In the past i've gotten that ID by just doing a SELECT with a WHERE that
matches all the values i've just INSERTED, but it seems a cumbersome
method.

Is there a better or 'right-way' to have this ID returned to me?

Thanks,

Ravenslay3r

Reply With Quote
  #2  
Old   
Aggro
 
Posts: n/a

Default Re: retrieving new record ID? - 07-18-2004 , 04:37 PM






Ravenslay3r wrote:

Quote:
Is there a better or 'right-way' to have this ID returned to me?
Many ways:
http://dev.mysql.com/doc/mysql/en/Ge...unique_ID.html

But you propably want to use this:
http://dev.mysql.com/doc/mysql/en/mysql_insert_id.html

Because:
"The value of mysql_insert_id() is affected only by statements issued
within the current client connection. It is not affected by statements
issued by other clients."

Which means, that if you have a php script like this:

<?php
open_connection_to_mysql()
insert_row_into_table()
call mysql_insert_id()
insert_row_into_second_table()
close_connection()
?>

It is safe to use mysql_insert_id(), even when there would be multiple
clients using the same script at the same time. Because client would get
the last id from her/his query, not from others queries.

But if you would use "select max(id) from table" or similar, you would
get wrong behavious if two clients would happen to be doing the same
thing at the same time.


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.