Stop data inserting into a database twice

2020-01-27 12:17发布

Im quite new to PHP, i was wondering what methods/preventions other programmers use to stop data being entered twice into a MySQL database when a user refreshes on the same page as a form? Obviouly it happens and i need a good way to stop this.

Thanks, Ben

16条回答
Rolldiameter
2楼-- · 2020-01-27 12:41

Add a hidden field with a random string (produced by md5(uniqid()) for example), make a field in the database for that string and make it UNIQUE.

查看更多
爷、活的狠高调
3楼-- · 2020-01-27 12:44

You have to pass an uniqid variable into your html inside the showAddProductForm() method and the same uniqid into your $_SESSION forexample:

public function showAddProductForm()
{
    $uniId = uniqid();
    $_SESSION['token'][$uniId] = '1';
    $fields['token'] = 'token['.$uniId.']';

    $this->fileName = 'product.add.form.php';
    $this->template($fields);
    die();
}

Then you have to put a hidden input in HTML code inside your form with the value of the uniqid that has been passed into the HTML from showAddProductForm method.

<input type="hidden" name="<?=$list['token']?>" value="1">

right after the submit event you will analyze it in the beginning of the addProduct() method. If the token exists in the $_SESSION and it has an equal value inside that array, then this is the new reques. Redirect him to the proper page and unset the token and continue insert. Else it is from the reloading page or a repetitive request, redirect him to addProdeuct page

public function addProducts($fields)
{
    $token_list = array_keys($fields['token']);
    $token = $token_list['0'];
    if (isset($_SESSION['token'][$token]) and $_SESSION['token'][$token] == '1') {
        unset($_SESSION['token'][$token]);
    } else {
        $this->addAnnounceForm($fields, '');
    }
}

Maybe you ask why an array of tokens why not a single variable. Because in admin Panel users open multi tabs and inserting in multi tabs so this algorithm will fail if they use multi tabs.

Special thanks to who figure out this method malekloo

查看更多
Animai°情兽
4楼-- · 2020-01-27 12:49

The best way to avoid duplicate record insertion on page refresh is, after inserting records in the database on button click, just add this line:

Response.Write("<script>location.href='yourpage.aspx'</script>");
查看更多
霸刀☆藐视天下
5楼-- · 2020-01-27 12:50

I usually rely on the sql UNIQUE index Constraint. http://dev.mysql.com/doc/refman/5.0/en/constraint-primary-key.html

查看更多
登录 后发表回答