How to Prevent Multiple Inserts When Submitting a Form in PHP

Prevent multiple SQL inserts

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.

Prevent multiple form submission on hitting enter twice

You can achieve this by jquery. Below is the same code.

In this example it will disable submit button for 2 seconds. After 2 seconds button will enable again. You can modify this according to your requirement.

$('form').submit(function(){
$(this).find(':submit').attr( 'disabled','disabled' );
//the rest of your code
setTimeout(() => {
$(this).find(':submit').attr( 'disabled',false );
}, 2000)
});

Try this and let me know if you have any concern.

How to prevent multi-click from submit with PHP?

It can be done in PHP, but I'd say your easiest option is to use javascript, and to simply disable the submit button on the first click.

Vanilla JS:

document.getElementById("yourButton").disabled = true;

jQuery:

$('#yourButton').attr("disabled", true);

Attach either function to your button's click event, and you're all set!

PHP Stopping a person pressing Submit multiple times

You can disable the submit button when submitting the form.

An example using jQuery:

<script type="text/javascript">

$(document).ready(function() {
$('#contactform').submit(function() {
$('input[type=submit]', this).prop("disabled", true);
});
});

</script>


Related Topics



Leave a reply



Submit