PDA

View Full Version : [PHP] Last_Insert_ID()



Wojtek
February 19th, 2004, 14:33
I need help on how to retrieve the last inserted unique auto-increment ID using the last_insert_id() function.



$query = "select last_insert_id() as $IDfinal";
$result = mysql_query($query);
echo "start <br> $IDfinal <br> end";

This code dosnt work, echo's nothing


Anyone could help me make it work

Canuckkev
February 19th, 2004, 16:55
Are you using Mysql?

http://ca3.php.net/manual/en/function.mysql-insert-id.php

Just use:



echo "last insert id is : " . mysql_insert_id();


That will only work if you JUST insterted a new entry...

Of course, if you just want the last id inserted, SELECT id FROM table ORDERY BY id DESC or something like that.

Wojtek
February 19th, 2004, 17:35
Excellent,

Thanks :)

CareBear
February 20th, 2004, 03:03
Originally posted by Canuckkev
Of course, if you just want the last id inserted, SELECT id FROM table ORDERY BY id DESC or something like that. There's no guarantee that if you insert a record and then issue that select statement that you'll get the unique ID for the record you just added since two people could be viewing the same page at once.
last_insert_id() works on the current connection, so it's safer to use :-)