Home >Database >Mysql Tutorial >How to Get the ID of the Last Updated MySQL Row Using PHP?

How to Get the ID of the Last Updated MySQL Row Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 08:03:10843browse

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:

  1. Set a User Variable: Create a user variable, @update_id, and assign it a value of 0.
  2. 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;
  3. Retrieve User Variable: Finally, execute a SELECT statement to obtain the value stored in the @update_id variable, which represents the ID of the last updated row.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn