Skip to content
Advertisement

Is there a way to differentiate between a page refresh and pushing a submit button?

I have a form that, when submitted with a button, adds an item to a SQL database. However, the problem is that if I refresh the page after submitting, it will add another identical item to this database. Is there any way to tell when a user is pushing a button and when they are just refreshing the page? I am aware that I could check each entry to see if it is identical to one already submitted, but I have had similar problems come up already in other programs and I would be grateful if I didn’t have to create a new workaround each time.

Code for reference:

<input type="text" name="var1" required>
<input type="text" name="var2" required>
<input type="text" name="var3" required>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if($_POST && isset($_POST['Submit'])) {
    $conn = mysqli_connect("localhost", "root",""); 
    mysqli_select_db ($conn,'database'); 
    $var1 =$_POST['var1'];
    $var2 = $_POST['var2'];
    $var3 = $_POST['var3'];
    $sql = "INSERT into database (var1,var2,var3) VALUES ('$var1','$var2','$var3')";
    if ($result = mysqli_query($conn, $sql)) { 
        echo("Item Added Sucessfully");
    }
}
?>

Advertisement

Answer

Trying to determine of a page is being refreshed or not is not the way to resolve this issue. What you need to do is prevent the browser from ever resubmitting that same form submission.

The Post/Redirect/Get pattern resolves this issue. Basically, after the form has been processed you want to redirect the user to the page you wish them to see by using a HTTP 303 redirect. This tells the browser to replace the form page in the browser history making it impossible to resubmit the form.

Here’s what it may look like in your code:

<input type="text" name="var2" required>
<input type="text" name="var3" required>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
if($_POST && isset($_POST['Submit'])) {
    $conn = mysqli_connect("localhost", "root",""); 
    mysqli_select_db ($conn,'database'); 
    $var1 =$_POST['var1'];
    $var2 = $_POST['var2'];
    $var3 = $_POST['var3'];
    $sql = "INSERT into database (var1,var2,var3) VALUES ('$var1','$var2','$var3')";
    if ($result = mysqli_query($conn, $sql)) { 
        header('Location: thankyou.php', true, 303);
        exit;
    }
}

FYI, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement