views:

121

answers:

2

Consider a simple schema of one to many relationship. Parent Table's Id is referenced in the Child table.

In php I want to insert a row into the table using the statement mysql_query($query). Then I will get the id of the last inserted row by using mysql_insert_id(). Then i will use this id to insert the another row into the child's table.

My question is that the since there could be multiple requests happening on the same time for a php page, what if the above two statements do NOT run one after the other (ie, for example, there are two inserts happening on the parent and then the two inserts on the child)? There could be concurrency issues. So how do we overcome this?

Any ideas?

+3  A: 

When you call mysql_insert_id() it gets the last inserted id for that connection, so two PHP scripts won't interfere with each other.

Greg
+2  A: 

As in MySQL documentation:

The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients.

So... no problem. Although, for other reasons, I recommend using ORM (like Doctrine).

Tomasz Struczyński
http://dev.mysql.com/doc/refman/5.0/es/mysql-insert-id.html
Tomasz Struczyński
So you mean that all ORMs (like Hibernate, Entity Framework(.net)) take care of this problem on its own?
Xinxua
I'm not sure about ALL of them, but I think most of. First of all, save process is often a batch in ORM (eg. you create object tree and then save it) so they have to deal with IDs somehow.But for details you'll have to see each one's manual, ofc :)
Tomasz Struczyński