Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to unsave if page refreshed

Tags:

html

php

mysql

I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.

current code:

<?php 
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');

$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
    $code=$rows['batchcode1'];
}

if(isset($_POST['save'])){
    $var = $code+1;
    $sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
like image 478
user3235574 Avatar asked Jan 27 '14 10:01

user3235574


1 Answers

The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.

If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.

To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.

Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.

like image 89
Konerak Avatar answered Sep 27 '22 17:09

Konerak