problem with form duplicity

0

I'm having a very common problem, and I do not know how to solve it. I will graze a page in php very simple to explain.

The problem occurs when the user submits the form, and when it clicks on the return address of the browser, the form is submitted again, generating a duplicate in the DB. Do you have any way to handle it?

Here is the code for my form:

<?php
//======================================================================================================================
// Envia formulário
//======================================================================================================================
if ((!empty($action)) and ($action === "add")) {

    // Recebe dados do formulario
    $nome = addslashes(filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_SPECIAL_CHARS));
    $idade = addslashes(filter_input(INPUT_POST, 'idade', FILTER_SANITIZE_NUMBER_INT));

    // Verifica se informou os dados
    if ((empty($nome)) || (empty($idade))) {
        ?>
        <script>
            alert('ERRO. Iforme todos os dados'); 
            history.back();
        </script>
        <?php
        die;
    }

    // Registra no BD
    $inserir1 = Query($mysqli, "INSERT INTO cadastro VALUES ('0', '$nome', '$idade')");

    // Verifica se cadastrou
    if ($inserir1) {
        ?>
        <script>
            alert('ERRO. Iforme todos os dados'); 
            window.location='cadastro.php';
        </script>
        <?php
    } else {
        ?>
        <script>
            alert('ERRO. Tente mais tarde'); 
            history.back();
        </script>
        <?php
    }
}
//======================================================================================================================
?>


<form name='form'  onsubmit='return validacao()' method=post action='cadastro.php?action=add' >

    <input  type="text" name="nome">
    <input  type="text" name="idade">

    <input type="submit" name="finalizar">
</form>
    
asked by anonymous 21.03.2017 / 21:24

2 answers

2

In this way, when you click on the back button of the browser, the session will prevent you from resubmitting the form and being resubmitted.

 <?php
 session_start();
 ...............
 ...............
  if ($_SESSION["nome"]==""){
   $inserir1 = Query($mysqli, "INSERT INTO cadastro VALUES ('0', '$nome', '$idade')");
   $_SESSION["nome"] = $_POST["nome"];
  }                
    
21.03.2017 / 22:47
1

A common way to resolve this problem is to redirect the user to the page itself to clear the post data:

//antes de qualquer saída (echo, caracteres etc)
//ao invés do window.location
header('Location:cadastro.php');

In your case you should also check if the request is POST or GET before processing the result:

if (!empty($_POST) && !empty($action) && $action === "add") {
    ...
    
21.03.2017 / 21:35