On 15 Dec 2004 19:02:08 -0800, "Ig" <blackgold00@yahoo.com> wrote:
[color=blue][color=green][color=darkred]
>> > Bruce Wolk wrote:
>> > > Sugapablo wrote:
>> > >
>> > >> Let's say I create a new record in a table like this:
>> > >> mysql_query("INSERT INTO table (col1) VALUES[/color][/color]
>('example')",$conn);[color=green][color=darkred]
>> > >>
>> > >> ...that had an auto-incrementing, unique identifying column[/color][/color]
>named "ID"[color=green][color=darkred]
>> > >> that would be populated with a unique number upon insertion...
>> > >>
>> > >> How can I get the unique number it assigned to that record[/color][/color]
>returned for[color=green][color=darkred]
>> > >> futher use?
>> > >>
>> > >>
>> > >
>> > > mysql_insert_id()
>> > >
>> > >
http://us2.php.net/manual/en/functio...-insert-id.php
>> > >
>> >
>> > Does mysql_insert_id() return the last record inserted by ANYONE,[/color][/color]
>or the[color=green][color=darkred]
>> > last record inserted by the current instance?>[/color][/color]
>
>Jim Thomas & All,
>
>The function that has been suggested does not seem to be what you want.
>Everyone with their manuals buzz off. This requires some logic.
>
>First, instead of relying on a one stop shop function to suit your
>needs you need to think beyond this. Imagine coming to a page for the
>first time that requires a customer ID. You could just rely on the dB
>to auto increment but then the user does know what the value is/was.
>
>Lastly, this is how I handle finding the last record auto incremented,
>increment it, and post it for a future query (You do not always need to
>rely on the system):
>
>$query = "select cust_id from customer_data order by cust_id DESC";
>$data_pointer = mysql_query($query);
>
>if ($getID = mysql_fetch_assoc($data_pointer))
>{
>$lastID = $getID[cust_id];
>$lastID++;
>print $lastID;
>}
>
>You may need to do some formatting with the value at he end of this but
>this code will lead you in the right direction.[/color]
This approach leads to a classic race condition. What's to stop another
session inserting this ID in the period between selecting and the time an
insert is done in this session? You'd have to lock the table to make this safe,
which limits your scalability.
And another point; why select ordered by a field descending, then select only
one row, when you could select max(field) instead, which is considerably more
efficient given the MySQL's client method of transferring the entire result set
to the client before allowing the first fetch (unless you use unbuffered
queries, which you haven't in the example).
--
Andy Hassall / <andy@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool