Is there any way to insert a row, and have it return a value from that row?
For example, I have a table where the PK is autoincrementing. I want to insert a row, and have it automatically return the auto-incrimenting ID number the DB gives it.
Is there any way to do this without running a separate select query afterwards?
Thanks!
-- Abe --
INSERT followed by SELECT
Moderator: General Moderators
-
Robert Plank
- Forum Contributor
- Posts: 110
- Joined: Sun Dec 26, 2004 9:04 pm
- Contact:
Exactly. Just as an FYI, the MySQL function LAST_INSERT_ID() will perform the same task, but within MySQL, e.g.Robert Plank wrote:mysql_insert_id() will give you the PK of the most recently inserted row if there is an autoincrement on the table.
Code: Select all
INSERT INTO `sometable` (`somefield`) VALUES ('devnetwork');
INSERT INTO `someothertable` (`sometable_ID`) VALUES (LAST_INSERT_ID());Note the difference: mysql_insert_id() will grab the last value whether you've used a NULL or 0 value to increment the column, OR simply left it out altogether and let MySQL perform the auto increment. LAST_INSERT_ID() will only use the value of the automatically inserted key.
MySQL manual: LAST_INSERT_ID()
PHP manual: mysql_insert_id()