Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does a sql query occur every time I reload the page?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading