[PHPwestoz] getting the last inserted id in mysql

Simon Marko s.marko at bigpond.com
Wed Feb 23 20:26:01 UTC 2005


Samuel Cochran wrote:

>
> Evan Barter wrote:
>
>> Samuel Cochran wrote:
>>
>>> Mike Fewings wrote:
>>>
>>>>> Unfortunately I don't know any function in MySQL that lets you 
>>>>> retrieve the auto-increment ID of a field you just created. You 
>>>>> normally have to do another select, which is not hard if you do 
>>>>> this: "SELECT ID FROM Artists ORDER BY ID DESC LIMIT 1" This will 
>>>>> give you the last created ID, which normally would be the last 
>>>>> record you created.
>>>>
>>>>
>>>>
>>>> This function can retreive the last insert id from the database
>>>>
>>>>                select last_insert_id() as feild_id
>>>>
>>>> and make this query immediately after the insert and it will return 
>>>> the last id that was inserted by auto increment.
>>>
>>>
>>> Alternatively, one can use the mysql_next_id() function of PHP. Have 
>>> a look: http://php.net/mysql-next-id
>>
>>
>> There's always mysql_insert_id() 
>> (http://au.php.net/manual/en/function.mysql-insert-id.php). But now 
>> I'm just being redundant. :)
>
>
> That's what I meant :$
>
> -- Sam
>
> _______________________________________________
> PHPwestoz mailing list
> PHPwestoz at lists.linux.org.au
> http://lists.linux.org.au/listinfo/phpwestoz
>
Another way of doing this could be:

Select max(id) from table_name

This assumes your auto_increment field is moving upward numerically (not 
always the case) - my experience is with Oracle where you use sequences eg:

create sequence my_seq;
insert into tablename (id,textybit) values (my_seq.nextval,'sometext'); 
--sequencename.nextval is a function to grab the next available value 
from the seq
select my_seq.currval from dual; --dual is a dummy table in oracle

--SimonM




More information about the PHPwestoz mailing list