Using mysql_insert_id

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Using mysql_insert_id

Post by GeXus »

Has anyone experienced problems when using mysql_insert_id? Such as the wrong id being grabbed? Perhaps on highly transactional sites? I haven't encountered anything, but I'm just wondering if it could pose a problem in the future
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Using mysql_insert_id

Post by RobertGonzalez »

There is a serious gotcha with mysql_insert_id as it relates to stored procedures/functions. Generally speaking the call to fetch the insert ID should be done immediately following the call that inserts. This usually alleviates clash, but not always.

If you can use a stored procedure, selecting the insert id immediately after the insert is a good bet that you will get what you are after.
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Re: Using mysql_insert_id

Post by GeXus »

What if it's just all inline?

I.e.,

Code: Select all

mysql_query("insert....");
$id = mysql_insert_id();
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: Using mysql_insert_id

Post by RobertGonzalez »

Right, that is what I am talking about... calling it immediately after the insert.
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Re: Using mysql_insert_id

Post by GeXus »

Ok cool thnx!
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Using mysql_insert_id

Post by Kieran Huggins »

make sure to reference the DB handle, or it will assume the last transaction, whatever it was.
Post Reply