1

I have fields added to database by user. After pressing the submit button, I redirect the page to another place, but if the user clicks back from the web browser, the same form comes and if he clicks the submit button again, the fields are added to the database. How can I prevent this?

Following my code:

HTML

<form action="index.php" method="post">
<input type="text" name="firstname">
<input type="text" name="lastname">
<button name="submitForm">Submit</button>
</form>

PHP

if (isset($_POST['submitForm'])) {

    $insert = $connect->prepare("INSERT INTO users (firstname,lastname) VALUES ('{$_POST['firstname']}','{$_POST['lastname']}')");
    
    $insert->execute();

    if($insert){
        header('Location:index.php?Status=True');
    }else {
        header('Location:index.php?Status=False');
    }

}
ADyson
  • 57,178
  • 14
  • 51
  • 63
JFeel
  • 189
  • 2
  • 10
  • If the session does not exist, allow the form, otherwise make a redirect. So have fun creating and using a session. – Salines Dec 08 '21 at 09:51
  • IMHO It's kind of the user's fault if they're silly enough to do that. It's just how the web works. – ADyson Dec 08 '21 at 09:56
  • **Warning:** Your code is vulnerable to SQL Injection attacks. It's not enough to prepare a statement - you have to use **parameters** in it to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli / PDO. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Dec 08 '21 at 09:57
  • See also [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Dec 08 '21 at 09:58

0 Answers0