In web applications, it's essential to address the common issue of accidental data duplication due to page refresh after form submission. The question arises when a form submission performs operations, such as database inserts, and subsequent refresh leads to undesired data redundancy.
To resolve this issue, it's best practice not to display the response on the same page after a submission. Instead, redirect the user to another page once the action is complete.
Consider the sample code provided in the question:
<?php if (isset($_POST['name'])) { // Database operation (e.g., inserting $_POST['name']) echo "Operation Done"; die(); } ?>
In this scenario, when you submit the form, the data is inserted into the database, and the user sees the message "Operation Done." However, if the page is refreshed after that, the form submission code will run again, potentially resulting in duplicate data insertion.
To avoid this problem, consider the following revised code:
<?php if (isset($_POST['name'])) { // Database operation (e.g., inserting $_POST['name']) // Set a success flash message (assuming you're using a framework) header('Location: /path/to/record'); exit; } ?>
Key Points:
The above is the detailed content of How to Prevent Accidental Resubmission on Page Refresh in Web Applications?. For more information, please follow other related articles on the PHP Chinese website!