php mysql防止快速表单提交中的重复插入

php mysql防止快速表单提交中的重复插入,php,mysql,forms,Php,Mysql,Forms,我正在使用以下代码进行测试: <?php $db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root'); if(filter_has_var(INPUT_POST, 'submit')) { $r = $db->query('SELECT * FROM test WHERE value="'.$_POST['value'].'"'); $n = $r->rowCount(); for ($i

我正在使用以下代码进行测试:

<?php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');

if(filter_has_var(INPUT_POST, 'submit')) {

  $r = $db->query('SELECT * FROM test WHERE value="'.$_POST['value'].'"');
  $n = $r->rowCount();

  for ($i=0; $i<=10000000; $i++) {
    // do nothing
  }

  if  (!$n) {
    $db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
  }

}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <input type="text" name="value" value="">
  <input type="submit" name="submit" value="Submit">
</form>
<?php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');

if(filter_has_var(INPUT_POST, 'submit')) {

  for ($i=0; $i<=10000000; $i++) {
    // do nothing
  }

  $r = $db->query('SELECT * FROM test WHERE value="'.$_POST['value'].'"');
  $n = $r->rowCount();

  if  (!$n) {
    $db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
  }

}
?>

通常,客户端
onsubmit
处理程序可以帮助阻止意外快速提交,但我通常选择使用
\u SESSION
变量的服务器端解决方案。只需创建
$\u POST
数组的散列,将其存储为会话变量,然后将下一个提交的
\u POST
与散列版本进行比较:

session_start();
//if this is the first time they've posted, just create a placeholder session var
if (!isset($_SESSION['repost_hash'])){$_SESSION['repost_hash']="";}

//if the post array is a duplicate, nullify the submission
if (isset($_POST) && md5(serialize($_POST)) == $_SESSION['repost_hash']){ 
   unset($_POST);
} else { //otherwise, if this is new data, update the stored hash
   $_SESSION['repost_hash'] = md5(serialize($_POST));
}
...

如果您只想在短时间内停止重复提交,还可以使用第二个
$\u SESSION
变量存储最后一次哈希的时间,这样您可以在一两秒钟后使其过期。

如果您不希望同一个值出现在表的多行中,则应在数据库中使用唯一约束设置它。