Darren
Darren

Reputation: 13

Prevent multiple SQL inserts

I currently have a JavaScript that resets forms if the page is refreshed or a user presses browser back button after submitting, but if an extremely bored user defies the JavaScript and fills in and submits a form over and over again, my DB will get spammed.

I would like to prevent this from happening (perhaps by checking if there have been inserted more than 10 rows from the same user within one minute or so) but I'm kinda clueless on what to do to prevent this.

Upvotes: 1

Views: 465

Answers (3)

I would add a column in your table that records the timestamp of the last form submission. Then, when your page loads, declare this as a global var for your javascript.

<?php include 'connect.php';

$sql = mysqli_fetch_assoc(mysqli_query($cxn, "SELECT lastFormSubmission FROM myTable WHERE login_id = '".mysqli_real_escape_string($cxn, $_SESSION['login_id'])."'"));

$lastFormTime = $sql['lastFormSubmission'];

?>

Now declare the time as a global var:

<script type="text/javascript">
    var lastTime = '<?= $lastFormTime ?>';
</script>

Now when your form script runs, you will need to choose a threshold time of what is "too often".

//Your script
var t = new Date().getTime() / 1000; //Need time in seconds to compare with timestamp


if (t - lastTime < yourThresholdTime) {
    //don't submit form
}

Upvotes: 0

Jeroen de Jong
Jeroen de Jong

Reputation: 337

Save the number of posts in a session variable.

Each time a user submits something you could do the following:

$_SESSION['postCount'] = $_SESSION['postCount'] + 1;

Then you change the whole thing to something like:

if($_SESSION['postCount'] > 2) {
  // Your code that posts to the database
  $_SESSION['postCount'] = $_SESSION['postCount'] + 1;
}

If you don't use sessions yet make sure that you start each script with session_start(); With this code no one can post something more than three times.

Upvotes: 2

nico
nico

Reputation: 143

Usually this is done with a session id/token.

This way you can check if its been submitted already and only allow it once.

Here is a similar question:

How to prevent multiple inserts when submitting a form in PHP?

Upvotes: 0

Related Questions