Re: Getting an Auto_Incremented ID from MySQL
- From: Michael Austin <maustin@xxxxxxxxxxxxxxxxxx>
- Date: Sat, 26 Jul 2008 14:43:46 -0500
KDawg44 wrote:
On Jul 26, 2:35 pm, KDawg44 <KDaw...@xxxxxxxxx> wrote:Hi,
I have PHP function that adds a record to the database. The table has
an ID that is AUTO_INCREMENT. Is there anyway to get that ID back
when I do any kind of insert? That ID is a foreign key that I need to
do an insert on afterwards.
Thanks.
Kevin
I found this documentation at http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
INSERT INTO foo (auto,text)
VALUES(NULL,'text'); # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
VALUES(LAST_INSERT_ID(),'text'); # use ID in second table
but my concern is that if two different people call this function at
almost the same time, it is possible (thought I do not know how
likely) that it could go something like this:
USER 1 INSERT
USER 2 INSERT
USER 1 RETRIEVE LAST_INSERT_ID()
What happens is that the first table creates a record and the second
table records various values for that record.
Table 1
ItemID ItemName ItemDesc
1 Foo Bar
2 Bar Foo
Table 2
ID ValueName Value Table1ID
1 A 5 1
2 B 5 1
3 A 5 2
4 C 5 1
5 B 5 2
So the PHP function performs gets passed the ItemName, Item Desc, and
the Values (array). It then performs an insert into Table 1, then
loops through the values array, inserting each into Table 2.
So what are the chances I can have the problem described above if I
did something like:
INSERT INTO Table1
$insertID = SELECT LAST_INSERT_ID()
Loop through array
INSERT INTO Table2 $valueName, $value, $insertID
Thanks.
Kevin
If I need to do multiple inserts into multiple tables using a web connection, I tend to incorporate all of the respective inserts for the logical transaction into a stored procedure where I guarantee that the connection being used for the subsequent inserts are the same as the connection for the initial connection and therefore guarantee that last_id is truly the last_id this connection executed. I do this to ensure that the complete transaction is autonomous - and if the complete transaction fails - it all gets rolled back.
There are many schools of thought on this, this is just how I prefer to execute this type of transaction. YMMV.
.
- References:
- Getting an Auto_Incremented ID from MySQL
- From: KDawg44
- Re: Getting an Auto_Incremented ID from MySQL
- From: KDawg44
- Getting an Auto_Incremented ID from MySQL
- Prev by Date: Re: Getting an Auto_Incremented ID from MySQL
- Next by Date: Re: CURL redirect not working even with CURLOPT_FOLLOWLOCATION set to true
- Previous by thread: Re: Getting an Auto_Incremented ID from MySQL
- Next by thread: Re: Getting an Auto_Incremented ID from MySQL
- Index(es):
Relevant Pages
|