Obtaining the ID of the Most Recently Updated Row in MySQL
When working with MySQL and PHP, it may be necessary to retrieve the ID of the last row updated within a query. This can be particularly useful for tracking changes made to the database. This question addresses how to accomplish this task effectively using MySQL in conjunction with PHP.
The provided solution involves utilizing a technique that involves the use of a user-defined variable (@update_id) and a combination of SQL statements. Firstly, the @update_id variable is initialized to 0. Following this, an UPDATE statement is executed, which sets the chosen column_name to the specified value while simultaneously setting the id column to the value of the @update_id variable. The WHERE clause limits the update operation to a specific row. Once the update operation is completed, a final SELECT statement retrieves the @update_id variable's value, representing the ID of the last updated row.
Additionally, the provided solution has been further expanded to support retrieving the IDs of multiple rows affected by an update statement. This is achieved by using a similar approach but utilizing the CONCAT_WS() function to concatenate the affected row IDs into a single string, separated by commas.
The above is the detailed content of How Can I Get the ID of the Most Recently Updated Row in MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!