1

Im new to PHP and I was wondering how I can overcome this seemingly simple problem:

I have a database with several tables. Of them 1 table is called "order_header". Order header has a field called "orderID" which is the primaryKey and is auto-incremented. OrderID is used in other tables in the database (food_table, drinks_table, merchant_info, customer_info, etc)and is unique to a particular order.

Now I insert data into the order_header using the usual INSERT statement and the order_header generates a new orderID. But now I need to retrieve the orderID I just created and use it to insert data into other tables of that database.

The question is how can I do both inserting data and retrieving the resulting orderID in one atomic method? I cannot use the mySQL query to get the last orderID because what if another thread has inserted an entry in orderID in the meanwhile.

In Java I guess one could use locks and the word @synchronized, but how would one do this in PHP?

1

1 Answer 1

5

Use mysql_insert_id straight after the query. It doesn't run another query to find the last ID

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer- quick question------but is that thread-safe and atomic? What is another thread inserts a record right after and then this statement executes, then don't I get the incorrect ID?
Yes - it returns the result for the last query on the current connection, since you call mysql_connect on each request, each "thread" has a different connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.