Get last inserted auto increment using php?
Posted: Sun Jul 29, 2007 6:00 pm
I've heard of using "mysql_insert_id", but is that the best way of getting the id of the last inserted row?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
SELECT max( id ) FROM `table`YesCitizen wrote:I've heard of using "mysql_insert_id", but is that the best way of getting the id of the last inserted row?
That's a waste of a query.Chalks wrote:The easiest way for an auto-increment is using max():Code: Select all
SELECT max( id ) FROM `table`
That's assuming you're using an id field that auto increments... which makes the last inserted the largest number.
That will get the id of the auto_increment column value in the left insert made using your current connection. If you want to get the id of the last inserted row regardless of connection then you should use a query to fetch MAX(`id`).Citizen wrote:I've heard of using "mysql_insert_id", but is that the best way of getting the id of the last inserted row?
Code: Select all
SHOW TABLE STATUS LIKE tablenameActually the surest way is to a database engine that supports transactions like InnoDB, and to use them.superdezign wrote:The surest way is to get the last entry that matches the data that you inserted into it (assuming all of them are generally unique). That's why I always use more information than I'll need, such as saving dates for almost all actions.
Or if we could run a SELECT and an INSERT / UPDATE at the same time.onion2k wrote:Actually the surest way is to a database engine that supports transactions like InnoDB, and to use them.superdezign wrote:The surest way is to get the last entry that matches the data that you inserted into it (assuming all of them are generally unique). That's why I always use more information than I'll need, such as saving dates for almost all actions.
Code: Select all
INSERT INTO `table` SET `foo` = 1 ALSO SELECT LAST_INSERT_ID() FROM `table`Transactions are a foreign concept to me... I should look into them.onion2k wrote:What would that return if the INSERT failed? In a transaction you could roll it back.