Question

Hello so I been trying to unset a post, basically the issue I am having is that the data gets INSERTED into the database. The php function sends out the message stating that the post was successful. That is all good but when I refresh my page, the post keeps on INSERTING data into my database. Basically how can I stop it from posting. Here is the code:

            if(isset($_POST['submit_message'])) { 
    $sql = "INSERT INTO messages (user_id, timestamp, times, message) 
    VALUES ('".$_SESSION['user_id']."', '".date("Y.m.d")."', '".date("H:i:s")."', '".$_POST['message-content']."')";

    $result = mysql_query($sql);
    unset($_POST['submit_message']);
    unset($GLOBALS['_POST']['submit_message']);
    if(!$result) {
        $msg = 'There was an error while trying add your message.'; 
        unset($_POST['submit_message']);            
    } else {
        $msg = 'Your message was successfully added.';      
        unset($_POST['submit_message']);        
    }
            }

As you can see from the code I tried inputting some unset posts using PHP but that does not seem to work. How can I unset my post?

Was it helpful?

Solution

Whenever you refresh the page, the form data is resubmitted. As a result $_POST is freshly populated with the form data. Remember, HTTP is stateless. Once the page executes and the request terminates the POST data from that request is gone.

If you do not want a page refresh to resubmit the form, you need to use the POST/REDIRECT/GET pattern.

In order for this to work properly we need to use a 303 redirect. This means we need to send a 303 header with our redirect. A 303 redirect will cause the browser to reload the page without the initial HTTP POST request to be resubmitted. This includes when the user uses the back or refresh buttons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top