title: php mysql prevent duplicate inserts from rapid form submits
body: <p>I'm testing with this code:</p>
  
  <pre><code>&lt;?php
  $db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
  
  if(filter_has_var(INPUT_POST, 'submit')) {
  
    $r = $db-&gt;query('SELECT * FROM test WHERE value="'.$_POST['value'].'"');
    $n = $r-&gt;rowCount();
  
    for ($i=0; $i&lt;=10000000; $i++) {
      // do nothing
    }
  
    if  (!$n) {
      $db-&gt;query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
    }
  
  }
  ?&gt;
  
  &lt;form method="post" action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;"&gt;
    &lt;input type="text" name="value" value=""&gt;
    &lt;input type="submit" name="submit" value="Submit"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>When testing the above form in safari I am able to submit the same value into my database multiple times by rapidly clicking the submit button.</p>
  
  <p>But, when I test with this code:</p>
  
  <pre><code>&lt;?php
  $db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
  
  if(filter_has_var(INPUT_POST, 'submit')) {
  
    for ($i=0; $i&lt;=10000000; $i++) {
      // do nothing
    }
  
    $r = $db-&gt;query('SELECT * FROM test WHERE value="'.$_POST['value'].'"');
    $n = $r-&gt;rowCount();
  
    if  (!$n) {
      $db-&gt;query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
    }
  
  }
  ?&gt;
  </code></pre>
  
  <p>The conditional works and I'm unable to submit the same value multiple times no matter how fast I click the submit button.</p>
  
  <p>Is there a reliable way to prevent duplicate database inserts from occurring with the first code snippet so that it behaves just like the second snippet?</p>