stop inserting data in the database when refreshin

2019-01-18 13:32发布

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?

9条回答
孤傲高冷的网名
2楼-- · 2019-01-18 14:09

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!

查看更多
男人必须洒脱
3楼-- · 2019-01-18 14:09

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'];        
} 
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-18 14:11

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

if (isset($_POST['submit'])) 
{
//do somthing
header("Location: $current_url");
}
查看更多
登录 后发表回答