-1

When I refresh my page, duplicate entries are entered into my MYSQL database via a form submission.

Anyway to prevent this?

Here's my form:

<form action="index.php" method="POST">
    <input type="text" name="GoodComment" maxlength="140" class="textBox">
    <input type="submit" class="button">
</form>

<div id="good">
<?php
fetchGood();
?>
</div>

Here's my INSERT code.

function fetchGood() {
   /*** INSERT data ***/
   $goodComment = $_POST['GoodComment'];
   $count = $db->prepare("INSERT INTO ProSubmissions(Comments) VALUES(?)");
   $count->execute(array($goodComment));

   /*** close the database connection ***/
   $db = null;

}

catch(PDOException $e) {

   echo $e->getMessage();

}

2 Answers2

0

Assuming that your ProSubmissions table only holds the columns "Timestamp" and "Comments", you could specify a combined unique constraint on those two columns, i.e. any combination of (Timestamp, Comments) has to be unique.

If my assumption is incorrect, please provide additional information.

oschlueter
  • 2,596
  • 1
  • 23
  • 46
0

It looks like you are running your insertion code without any indication from the end user that the form has been filled. The fetchGood() function should be called when the submit button is pressed, not immediately after the form is generated. You may have more luck attaching the function to an ajax method that is submitted to the server when the submit button is clicked. Please view this thread for more info on how to accomplish this:

How to call a PHP function on button click

As others have stated, adding a multi-column unique index in your database will prevent duplicate records, and this precaution should also be taken.

Please also note that you should be sanitizing your data before it is passed to the database. This is not really part of your question, but it is very important. End users should not be allowed to enter data into your database that has not been checked for malicious input and poorly formed submissions that may cause problems elsewhere when the record is recalled. At the very least you should be removing script tags so people do not post comments that redirect your viewers to malicious websites or otherwise hijack their browser. Please also read the comments in this thread for a better understanding on how to accomplish this:

Sanitizing data in PDO

Community
  • 1
  • 1
mopsyd
  • 1,877
  • 3
  • 20
  • 30