How to not allow repeated INSERT by giving Reload on the page?

Asked

Viewed 1,372 times

3

How can I not allow INSERT repeated if someone re-loads the page?

Example:

$libera = $_POST['libera'];

if ($libera == "sim"){
    $sql = mysql_query ("INSERT INTO a_finan(id_reserva,id_cliente)VALUES('$id_res','$id_cliente')", $conexao) or die( mysql_error());
}else{
    echo"";
}

If I give a submit to execute this code, after it is executed, if you give a Reload on the page it runs again. How to avoid this?

  • 5

    Maybe it’s a duplicate of Form inserting twice in bank F5

  • 2

    Definitely a duplicate. The 3 answers there are almost identical to the one we posted here. Funny that the reply from @Bruno Augusto shows how to do with Session, the same that I showed here. But there is no negative. rsrs..

3 answers

5

As @Inkeliz said, you can check if the record already exists before entering.

Another thing I do and recommend is: after an insert, redirect to the listing of what was entered, for example, if a product was inserted, then redirect to the product listing, so if the user reloads the page he will reload the listing and not the insertion.

To redirect in PHP (added exit at the suggestion of @Acco)

header('Location: destino.php'); 
exit; // para garantir que o script termine aqui
  • 1

    +1! Redirect is my preferred solution.

  • In this case I believe it would be better to add the header("HTTP/1.1 301 Moved Permanently");, because the user could return the previous URL, some browsers display "want to resend"for example. If you use 301 generally the browser caches the redirect, tending to redirect whenever you log in or try to resend, but it’s also not right. I believe that because of doubts to make both solutions would be ideal.

2


You can check if these values already exist.

For example:

<?

$libera = $_POST['libera']; 
if ($libera == "sim"){

// MODIFICAÇÃO

$sqlChecar = mysql_query("SELECT id FROM a_finan WHERE id_reserva = '$id_res' AND id_cliente = '$id_cliente'");
// Irá buscar os registros

if(mysql_num_rows($sqlChecar) === 0){
// Se não houver resgistros faça...

// FIM DA MODIFICAÇÃO 

$sql = mysql_query ("INSERT INTO a_finan(id_reserva,id_cliente)VALUES('$id_res','$id_cliente')", $conexao) or die( mysql_error());
// Insere normalmente

}else{
//se não

echo "Já existe";


}
}else{
echo ""
}

This way you will check, before entering, if there is already a record with the same values.

mysql_* is already obsolete and I don’t recommend it if it’s at the beginning of development (or it’s just learning) try mysqli. Remember that no type of security feature has been used!

  • 2

    mysqli_* or tb PDO.

  • 1

    @Diegofelipe PDO would complicate for nothing. And mysqli besides everything has real parameters Binding, PDO only simulates. The only situation I can imagine to use PDO instead of mysqli is if the author needs the application to work in several different banks (but this is rare).

  • I believe that the advantage of PDO is to support banks other than Mysql. It is not invalid solution because it also supports, but its advantage in this case is not useful. So suggest mysqli_*

2

The simplest is to redirect to another page, however, the user can still turn the page and reprocess it.

To provide a greater guarantee, raise a flag using session variable:

if ($libera == "sim" && !isset($_SESSION['submitted'])){
    $sql = mysql_query ("INSERT INTO a_finan(id_reserva,id_cliente)VALUES('$id_res','$id_cliente')", $conexao) or die( mysql_error());

    $_SESSION['submitted'] = true;
}else{
    echo "";
}

On the form page, put:

<?php
if (isset($_SESSION['submitted'])) {
    unset($_SESSION['submitted']);
}

This serves to reset the flag and be able to post legitimately from the form if the user wants to register something else, not duplicated.

Starting the session

Of course, you should know that for the use of session variables you need to initialize them with session_start().

I omitted the startup in the above examples as it may be that your system is already using and this could cause some error. If your scripts are not using, simply invoke the function:

On the form:

<?php
session_start();
if (isset($_SESSION['submitted'])) {
    unset($_SESSION['submitted']);
}

In the script that receives the data and writes:

session_start();
if ($libera == "sim" && !isset($_SESSION['submitted'])){
    $sql = mysql_query ("INSERT INTO a_finan(id_reserva,id_cliente)VALUES('$id_res','$id_cliente')", $conexao) or die( mysql_error());

    $_SESSION['submitted'] = true;
}else{
    echo "";
}

Let’s complicate the matter?

The user can still backward and forward (retouch and forward) through the browsing history. In this case, the user is kidding. But it could be legitimate. It is possible to implement more reinforcement in these cases using the session variable, for example, by checking whether the data sent is exactly the same as previously sent.

Use advantage

This is not the case for the question here, but for cases where there is no primary key control to be inserted, it would not be feasible to use the database search technique before inserting because without a single key it would make the search query more complex and often inaccurate.

Example of situation: a table with a primary key of the autoincrement type.

The session technique also helps prevent actions from bots and spammers as a session must be started on the form’s original page. It doesn’t mean it’s 100% safe from bots or spammers, but it helps to make such actions more difficult.

Additional notes

A session variable expires, but still better than having nothing. In addition a session can be set to expire in a time greater than 1 hour. One day for example. For even greater reinforcement, you can use $_COOKIE, instead of Session. Then let’s hear that the user can delete the cookie. Ok, but then it’s no longer an ordinary user and it’s clear the bad intention. For such a user, you can put whatever block you find a way around. In these cases it is good to guard against suspicious activities and take appropriate measures. At this point we entered into a parallel discussion, which we should not add here because it would deviate much from the main focus, branching out to various subjects.

  • 2

    I did not understand the negative. Who voted could explain where he saw reason for such..

  • 2

    I didn’t vote no! But SESSION may expire if the user keeps the page open for a long time and then returns it can re-enter.

  • A session variable expires, but still better than nothing. In addition, a session can expire in a time greater than 1 hour. A day for example.

  • I added to the answer that subject you commented on, @Inkeliz, as well as other obvious remarks.

Browser other questions tagged

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