How to get ID of the last updated row in MySQL?
To get the ID of the last inserted row, you can use the LAST_INSERT_ID()
function. For example:
INSERT INTO table (col1, col2) VALUES(val1, val2);
SELECT LAST_INSERT_ID();
This will insert a new row into the table
table and then return the ID of the last inserted row.
If you want to get the ID of the last updated row, you will need to modify your query to include the LAST_INSERT_ID()
function in the WHERE
clause of the UPDATE
statement. For example:
UPDATE table SET col1 = val1, col2 = val2 WHERE id = LAST_INSERT_ID();
SELECT LAST_INSERT_ID();
This will update the row with the ID equal to the last inserted ID, and then return the ID of the last updated row.
Note that the LAST_INSERT_ID()
function returns the last ID generated by an INSERT
or UPDATE
statement on the current connection, so you will need to make sure that you are using the correct connection when executing this function.
I hope this helps! Let me know if you have any questions.