Home > Database > Mysql Tutorial > body text

How to Retrieve the Updated Value After a MySQL UPDATE Operation?

Susan Sarandon
Release: 2024-10-28 14:43:02
Original
581 people have browsed it

How to Retrieve the Updated Value After a MySQL UPDATE Operation?

Retrieving Updated Value from MySQL

When performing an update operation in MySQL, the affected rows count is typically returned by default. However, there are scenarios where it's desirable to retrieve the updated value instead.

Consider the following query:

UPDATE item SET `score`=`score`+1 WHERE `id`=1
Copy after login

This query increments the score of an item with the specified ID. By default, the result of executing this query would be the number of rows affected, which is 1 in this case.

However, to retrieve the updated value, a stored procedure can be utilized. A stored procedure allows you to execute a set of SQL statements as a single unit and can be defined as follows:

<code class="sql">DELIMITER $$   -- Change DELIMITER in order to use ; withn the procedure
CREATE PROCEDURE increment_score
(
   IN id_in INT
)
BEGIN
    UPDATE item SET score = score + 1 WHERE id = id_in;
    SELECT score AS new_score FROM item WHERE id = id_in;
END
$$            -- Finish CREATE PROCEDURE statement
DELIMITER ;   -- Reset DELIMITER to standard ;</code>
Copy after login

This stored procedure first updates the score and then selects the new value into an output parameter named new_score. In PHP, you can call this stored procedure and retrieve the updated value as follows:

<code class="php">$result = mysql_query("CALL increment_score($id)");
$row = mysql_fetch_array($result);
echo $row['new_score'];</code>
Copy after login

By using a stored procedure, you can execute both the update and retrieval operations within a single query, reducing the number of queries and improving performance.

The above is the detailed content of How to Retrieve the Updated Value After a MySQL UPDATE Operation?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!