views:

34

answers:

2

I want to use PHP and MySQL to insert data into a data table and its associated many-to-many table. The auto-incrementing primary ID of the data table is used in the many-to-many table. So, I need to know the ID's of the data table to insert into the many-to-many table.

My current thinking is that the best way to approach this is with a loop, which would first insert into the data table then use mysql_insert_id() to insert into the many-to-many table. Is that the best way to go about this?

Additionally, do I need to be concerned about getting the wrong id with that function? Many workers would be using this data script at the same time, so my concern is that an ID from one workers query would end up being returned in the call to mysql_insert_id() of another. Is that a valid concern and if so how can I deal with it?

+3  A: 

Calling mysql_insert_id() on a table with an auto_increment id is exactly the right approach.

As long as you call mysql_insert_id() straight after you call mysql_query() to insert the row, you don't need to worry about getting the wrong id. PHP and MySQL look after all that for you.

Gus
A: 

If you can just lock the table.

LOCK TABLE myTable FOR WRITE;
SELECT MAX(id) FROM myTable;
INSERT....
INSERT....
INSERT....
SELECT MAX(id) FROM myTable;
UNLOCK TABLES;

This will prevent anyone else from doing anything with myTable, but you will then have the min/max range for your ids.

-daniel

Daniel
-1: a) mysql_insert_id is already thread-safe, as pointed out by Gus and staticsan. b) This will be a performance hog or no reason. The question implies multi-threaded access. c) Using MAX(id) is a bad idea. Although an auto-incremented ID is often defined as MAX(column)+1, for example in MyISAM, you should not rely on it for portability reasons. d) The question implies that the result for each insert is needed, not just the last insert.
EboMike
b) Tables can be locked for short periods of time. c) Yes, MAX(id) is a bad idea in regards to portablility, but who changes databases? It's a rare event. d) The result is the all of the inserted values from the start SELECT MAX(id) to the end SELECT MAX(id).
Daniel
-1: on self. I should have read the question more carefully. :)
Daniel