How to refresh page and not send duplicate data to PHP database?

Asked

Viewed 1,861 times

5

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

In case the user refreshes the page, after sending the first form, the data is not sent again to Mysql.

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

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

2 answers

7

An alternative:

is you create a session variable to check if there has already been a request, 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: http://wbruno.com.br/php/diferenciar-refresh-f5-de-postsubmit/

  • I just didn’t vote because I need 15 points!

5

One solution is to make a redirect right after entering the information in the bank. Even if the user refreshes the page the POST sent before will not be resubmitted 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
 } 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.