How to refresh page and not send duplicate data to the bank in PHP?

5

I would like to know if someone has an example or can explain me in the following question:

In case the user refreshes the page, after submitting the first form, the data is not sent back to MySQL.

My application is in PHP, I already researched, but I still can not solve it.

The application consists of 5 forms in a single table, but the fill is one by one.

    
asked by anonymous 03.03.2015 / 02:23

2 answers

7

Another alternative:

You create a session variable to check if a request has already been made, see:         

        if( $_SERVER['REQUEST_METHOD']=='POST' )
        {
            $request = md5( implode( $_POST ) );

            if( isset( $_SESSION['last_request'] ) && $_SESSION['last_request']== $request )
            {
                echo 'refresh';
                // opa! é refresh!
            }
            else
            {
                $_SESSION['last_request']  = $request;
                echo 'é post';
                //salva o que tem que ser salvo
            }
        }
    ?>

Source: link

    
03.03.2015 / 04:33
5

One solution is to make a redirect right after entering the information in the database. Even if the user refreshes the page the POST sent before will not be resent by the browser.

Example:

<?php

if(isset($_POST['....'])) {
 // salva no banco
 if($salvou_no_banco) {
   // redireciona para a mesma página (algo como um "refresh")
   header('Location: ' . $_SERVER['REQUEST_URI']); 
 } else {
   // algum erro! carrega a mesma página novamente
   // se o usuário atualizar aqui o máximo que vai acontecer é receber o erro novamente
 } 
}
    
03.03.2015 / 02:36