-1

Whenever I submit a feedback in my php page, it records the text in the database however when i refresh my page the data in the mysql database duplicates. What is wrong with my code?

<?php
include('session.php');

if(isset($_POST['submit'])){
    $fidbak = mysqli_real_escape_string($db,$_POST['fidbak']);
    $sql = "INSERT INTO tblfeedback VALUES ('$user_check', 
'$FirstName $MiddleName $LastName', '$fidbak')";
    $result = mysqli_query($db,$sql) or die(mysql_error());
}
?>

<!doctype>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/feedback.css">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <form action="" method="POST">
</head>
<body>
    <div class="mainDiv">
        <div class="mainFeedback">
            <div class="fback">
                <textarea rows="20" cols="65" placeholder="What can we do?" name="fidbak"></textarea>
                <button id="subm" type="submit" name="submit">Submit</button><br><br>
                </span>
            </div>
        </div>
    </div>
    <script src="sameFunctions.js"></script>
    <script src="js/fback.js"></script>
</body>
</html>
PlusUltra
  • 31
  • 8
  • why are u using `type="submit"` with ` – devpro Jan 28 '19 at 14:52
  • Because you're resending the same POST data by doing a refresh. The browser will often confirm this with you before repeating the request. You can stop this by redirecting the user after finishing processing the POST request. – Jonnix Jan 28 '19 at 14:54
  • https://en.wikipedia.org/wiki/Post/Redirect/Get – 04FS Jan 28 '19 at 14:55
  • If you access the page directly, it won't insert. If you're refreshing (and not going to it again), you'll resend the POST data. Look into Post-Redirect-Get pattern, or use a framework to handle it for you. – Qirel Jan 28 '19 at 14:56
  • Refresh resends the page. Hence the script runs again – RiggsFolly Jan 28 '19 at 15:21

1 Answers1

0

Make redirect to same url with GET-method right after successfully POST-request.

So yours PHP-chunk(that handles POST-request) will be somewhat like this:

<?php
include('session.php');

if(isset($_POST['submit'])){
    $fidbak = mysqli_real_escape_string($db,$_POST['fidbak']);
    $sql = "INSERT INTO tblfeedback VALUES ('$user_check', 
'$FirstName $MiddleName $LastName', '$fidbak')";
    $result = mysqli_query($db,$sql) or die(mysql_error());
    header('Location: ' .  $_SERVER['PHP_SELF'], true, 307);
}
?>
Jigius
  • 325
  • 4
  • 10