Home >Database >Mysql Tutorial >How to Get the ID of the Last Updated MySQL Row Using PHP?
Retrieving the ID of the Last Updated MySQL Row with PHP
Question: How can you programmatically obtain the ID of the last updated row in a MySQL database using PHP?
Answer: To retrieve the ID of the last updated row in MySQL using PHP, you can employ the following steps:
Execute Update Statement with Subquery: Run an UPDATE statement on the target table, setting a column value and simultaneously assigning the old value of a specific column to the @update_id variable. For example:
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id) WHERE some_other_column = 'blah' LIMIT 1;
Additional Note: To retrieve multiple updated IDs from an UPDATE statement, you can use a variation of the technique above:
SET @uids := null; UPDATE footable SET foo = 'bar' WHERE fooid > 5 AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) ); SELECT @uids;
This will return a comma-separated list of IDs of all rows affected by the update.
The above is the detailed content of How to Get the ID of the Last Updated MySQL Row Using PHP?. For more information, please follow other related articles on the PHP Chinese website!