Getting Primary ID of row just inserted into MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
real246
Forum Newbie
Posts: 3
Joined: Mon Mar 31, 2008 2:50 am

Getting Primary ID of row just inserted into MySQL

Post by real246 »

How do I retrieve the Primary ID of a row that I just inserted into a MySQL v5 table when the primary ID is set to auto increment and the value is set to INT of the primary ID?

Any help would be greatly appreciated.

Thank you.
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: Getting Primary ID of row just inserted into MySQL

Post by aceconcepts »

The following will return the most recent mysql insert:

Code: Select all

 
$id=mysql_insert_id();
 
real246
Forum Newbie
Posts: 3
Joined: Mon Mar 31, 2008 2:50 am

Re: Getting Primary ID of row just inserted into MySQL

Post by real246 »

can i be reasonably guaranteed that if I put the INSERT record a few lines before I call the most recent mysql insert that it will be the one that I just inserted? Reason I ask is because the database is being updated simultaneously by other users constantly. Wondering if this might possibly interfere?

example:

insert record here

call most recent record id here


Thank you
User avatar
aceconcepts
DevNet Resident
Posts: 1424
Joined: Mon Feb 06, 2006 11:26 am
Location: London

Re: Getting Primary ID of row just inserted into MySQL

Post by aceconcepts »

Your example is correct
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Getting Primary ID of row just inserted into MySQL

Post by John Cartwright »

mysql_insert_id() fetches the last inserted id from your connection
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Getting Primary ID of row just inserted into MySQL

Post by RobertGonzalez »

Take note that this function does not work when calling it against an insert stored procedure.
Post Reply