Home > Backend Development > PHP Tutorial > How to Get the ID of the Last Updated MySQL Record Using PHP?

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

Patricia Arquette
Release: 2024-12-25 13:48:31
Original
713 people have browsed it

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

How to Retrieve the ID of the Most Recently Modified Record in MySQL with PHP

In this guide, we will explore a practical method for obtaining the ID of the last row that was updated in a MySQL database using PHP.

The SQL statement presented below effectively sets an internal variable called @update_id to 0. Subsequently, it proceeds to update a given row in a specific table, with its ID being set to the value of @update_id. This value is obtained as the ID of the row being modified. Finally, the value of @update_id contains the ID of the most recently updated row.

SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1; 
SELECT @update_id;
Copy after login

Extended Technique for Retrieving Multiple IDs After an Update:

An enhancement to this technique enables you to retrieve the IDs of all rows affected by an update statement.

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;
Copy after login

This modified code results in a string where all the IDs are comma-separated.

The above is the detailed content of How to Get the ID of the Last Updated MySQL Record Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template