I have 2 steps in my database. first a record is inserted in a reference table. the key is autoincrement.
the key of the new inserted record must be added in a field in another table. is there a simple way to retrieve the number of the last inserted key ????
Keep in mind that skiflyer's advice is not concurrency-safe.
It is very possible on a busy site that your script can insert a record, and that before it can issue the "SELECT MAX(<key_field>)..." query, another script can have inserted another record into the same table. In that case, you will not get the index of the record you inserted, but the index of the record the other user inserted. Want the best answers? Ask the best questions:
is there a concurrency safe version that works for all databases?
I can't think of one... mssql has the one you mentioned, oracle lets you use whateverthosecounters are called... sequences or something... drawing a blank on others though.
MySQL supports a field property called auto_increment, if that's what you mean. It's a requirement if you are going to use PHP's mysql_insert_id() function. Want the best answers? Ask the best questions:
Unimportant at this point, but for my own edification I was wondering if there was a solution as elegant as mysql_insert_id() that worked on all SQL compliant databases.
Other database servers can do the same thing by using two queries in a single transaction. The trick is to make the insert of data and the retrieval of the insert id an atomic operation.
PHP's mysql_insert_id() uses a feature that is specific to MySQL -- you can duplicate the return of this function by performing "SELECT LAST_INSERT_ID()". That builtin function is a workaround of the fact that MySQL does not as yet suppport transactions well.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.