0

I am trying to build a forum, here is a page of the forum, there is a form for adding questions to the forum. When I submit the form it adds the question to the database but every time I reload the page it adds the same question. how can I solve it? thanks

$connect = mysqli_connect("localhost","root","","forum");
        if(isset($_SESSION['user_id'])){
            $user_id=$_SESSION['user_id'];
            echo '<div class="ask_question_div"><form method="post" class="add_question_form" action="">
                         answer <input name="answer" />
                            <input type="submit" name="submit_answer" value="create question" />
                         </form></div>';
    
                 if(isset($_POST['submit_answer']))
                {
                    if(empty($_POST['answer']))
                    {
                        echo '<span class="error_field">some field are empty</span>';
                    }
                    else{
                        $insert_answer_sql = "INSERT INTO posts (post_id,post_content,post_date,post_topic,post_by) VALUES ('',?,now(),?,?)";
                        $stmt = mysqli_stmt_init($connect);
                        mysqli_stmt_prepare($stmt,$insert_answer_sql);
                        mysqli_stmt_bind_param($stmt,"sss",$_POST['answer'],$_GET['question'],$user_id);
                        if(mysqli_stmt_execute($stmt))
                        {
                        echo 'success';
                        }
                        else {
                            echo 'error';
                        }
                    }
                }
                
            }

Thanks all!

Ofek
  • 47
  • 7

1 Answers1

0

This is because on refresh, $_POST is resubmitted and there is nothing in your code to catch the re-submission.

There are two ways you can alleviate this, either use the POST/REDIRECT/GET method or simply clear the page state with JS, eg.

<script>
  if(window.history.replaceState){
    window.history.replaceState(null, null, window.location.href);
  }
</script>

Which will clear the $_POST variable, hence refreshing the page will not re-submit the $_POST var.

PavKR
  • 1,591
  • 2
  • 11
  • 26