10

I am looking for a way to stop inserting or sending data in the database when refreshing the page.

here is my code:

user_details_page.php

<form action="confirm_page.php" method="post" >
User Name:  
<input  type="text" name="username" >
User Email
<input  type="text" name="useremail" >
Password:  
<input  type="text" name="password" >
<input type="submit"  name="submit" >
</form>

confirm_page.php

if (isset($_POST['submit'])) 
{
$user= $_POST['username'];
$email = $_POST['useremail'];
$pass= $_POST['password']; 

mysql_query("INSERT INTO table (username, useremail, email) VALUES ('$username','$useremail','$email');

}

so the problem everytime I refresh the confirm page.php the data is sent to the database. how to stop this?

Mj Jam
  • 173
  • 4
  • 6
  • 16

11 Answers11

19

Header the user to a new page :

if (isset($_POST['submit'])) 
{
  $user= $_POST['username'];
  $email = $_POST['useremail'];
  $pass= $_POST['password']; 

  mysql_query("INSERT INTO table (username, useremail, email) VALUES(`$username','$useremail','$email')");

}
//best outside the if statement so user isn't stuck on a white blank page.
header("location: landing_page.php");
exit;

By doing this the user who refreshes will be refreshing landing_page.php which means it won't do the insert twice.

best advice: do a check to see if user exists first if so don't insert!

Sir
  • 8,135
  • 17
  • 83
  • 146
  • **Warning:** You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](http://php.net/manual/en/pdo.prepared-statements.php) or by [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Never trust any kind of input, especially that which comes from the client side. Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). – Dharman Mar 15 '19 at 21:40
  • 1
    If he's still not using something like PDO 5 years after this post thats his own fault at this point. – Sir Mar 16 '19 at 00:30
2

What is going on here is that when you refresh page, the form is submitted twice.

To prevent this, you can use sessions:

session_start();

if( $_SESSION['submit'] == $_POST['submit'] && 
     isset($_SESSION['submit'])){
    // user double submitted 
}
else {
    // user submitted once
    $_SESSION['submit'] = $_POST['submit'];        
} 
jh314
  • 27,144
  • 16
  • 62
  • 82
0

Once an insert or update is done in your code you always need to redirect to another page.

See here on how to do that: How to make a redirect in PHP?

(You want to use a PHP redirect, not a Javascript or HTML one, because you obviously really need this to work.)

The confirm page should be what you redirect to after the update, not what does the insert.

Community
  • 1
  • 1
developerwjk
  • 8,619
  • 2
  • 17
  • 33
  • Not true - that can work but there's lots of times where you need to stay on same page – anoldermark Feb 03 '17 at 16:06
  • @mark If want to stay on the same page either use Ajax or redirect back to the same page with different parameters, but if you did a normal HTML submit and don't redirect and someone refreshes the page then the same parameters are resent and you get a double submit of that data. – developerwjk Feb 08 '17 at 20:52
0

The best way to prevent that is to add header('Location: filename') after your query. Thus in your case,

if (isset($_POST['submit'])) 
{
$user= $_POST['username'];
$email = $_POST['useremail'];
$pass= $_POST['password']; 

mysql_query("INSERT INTO table (username, useremail, email) VALUES ('$username','$useremail','$email');
//must be inside the condition to prevent too many redirects
header('Location: user_details_page.php');
}
0

confirm_page.php:

if (isset($_POST['submit'])) 
{
$user= $_POST['username'];
$email = $_POST['useremail'];
$pass= $_POST['password']; 

mysql_query("INSERT INTO table (username, useremail, email) VALUES ('$username','$useremail','$email')"); // <-- missing endquote and bracket here

header('Location: somewhere_else.php');
exit;
}
Sammitch
  • 30,782
  • 7
  • 50
  • 77
0

i have this solution by using session

<?php session_start();
        if(isset($_POST[$_SESSION[a][count($_SESSION[a])-1]])){
            echo "somthing....";
            unset($_SESSION[a]);
        }
        else{     
                        echo '<form method="post">';
                              $_SESSION["a"]=array();
                              $_SESSION["a"][0]="a".rand(1,100);
                        echo '<input name="'.$_SESSION["a"][0].'"><br>';
                              $_SESSION["a"][1]="a".rand(1,100);
                        echo '<input name="'.$_SESSION["a"][1].'"><br>';
                              $_SESSION["a"][2]="a".rand(1,100);
                        echo '<input name="'.$_SESSION["a"][2].'"><br>';
                              $_SESSION["a"][3]="a".rand(1,100);
                        echo '<input type="submit" name="'.$_SESSION["a"][3].'" value="submit"><br>';
                        echo '</form>';
        }               
?>
hazem
  • 27
  • 2
  • 5
0

We can stop it without redirect , best way to use PHP $_SESSION like this :

if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_SESSION['form_submit']) )
{ 
    extract($_POST);
    $sql=""INSERT INTO table (username, useremail, email) VALUES('$username','$useremail','$email')";
    $_SESSION['form_submit']='true'; 
} 
else
 {
    $_SESSION['form_submit']='NULL';
 }
Ak Memon
  • 29
  • 6
0

The fast way is to redirect the page to it's current location:

if (isset($_POST['submit'])) 
{
//do somthing
header("Location: $current_url");
}
Eyal Sooliman
  • 1,876
  • 23
  • 29
0

I was facing the same problem. Was trying to add some data and everytime when I refreshed the page it gets added again. It happens because the page is not loading. For that you need to add:

<?php ob_start();?> in your header file, then include the header in the current file you are working on. After that use the below code

    if (isset($_POST['submit'])) 
{
  $user= $_POST['username'];
  $email = $_POST['useremail'];
  $pass= $_POST['password']; 

  mysql_query("INSERT INTO table (username, useremail, email) VALUES(`$username','$useremail','$email')");

//user it before if statement
header("location: onthesamepage/oranyotherpage.php");
}
jsLearner
  • 159
  • 3
  • 11
0

index.php

Facing Same Problem Solution | IF you using ( ) outside query when don't use backtick in values use ' ' single quote.

<?php 
  include 'connection.php';

 if(isset($_POST['submit'])){
     $username = $_POST['username'];
     $password = $_POST['password'];

    $query = "INSERT INTO`login`(`username`,`password`)
                        VALUES('$username','$password')";  
    $insert_data= mysqli_query( $connection,$query);
     }
   ?>

form

<form method="post">
      <br><br>
    <div class="card">
        <div class="card-header bg-dark">
            <h1 class="text-white text-center">Insert Opration</h1>
            <h2><a href="display.php">Data</a> </h2>
        </div>
          <label for="username">Username</label>
          <input type="text" name="username" class="form-control"><br>

          <label for="password">Password</label>
          <input type="password" name="password" class="form-control"><br>

          <button class="btn btn-success" name="submit" type="submit">Submit</button> 
    </div>
    </form>
Sarthak Raval
  • 1,001
  • 1
  • 10
  • 23
-1
if($_POST(submit)
{
 //database insertion query
 // if successful insertion
    {
echo"<script language='javascript'>alert('successfully inserted')</script>";
echo"<script>document.location='your_page.php';</script>;
    }
}