Skip to content
Advertisement

PHP form data reinserting input into WordPress database each time page is refreshed [closed]

I am having a problem when submitting and passing information from an HTML form into a WordPress database. I am using <form method="post">. The form inputs are successfully inserted into the database; however, when I click refresh on the browser, the same data from the previous submission is re-inserted in the table, and is done so each time the page is refreshed. If I exit the browser, this stops the error; however, I do not want to have to close the browser each time I enter the information.

I am not sure if the problem is in the HTML, or the PHP.

I have also tried using wp_redirect($url); exit; (redirecting to the same page), in the hopes that the redirect will clear any code that was stuck in the browser from the first submission. However, that does not fix the problem either.

Is there a way to clear the data so that when I press refresh, nothing further is submitted, until I manually fill out the form, and then re-submit?

I have tried coding wp_redirect($url); exit; after in the HTML portion of my template page. Should I be placing this code somewhere else in the PHP file?

Advertisement

Answer

I was able to solve the problem by placing the wp_redirect( $url); exit(); code within my theme’s functions.php file.

if (isset($_POST['submitCOGS'])){
    $data = array (
        'date' => $_POST['date'],
        'source' => $_POST['source'],
        'items_purchased' => $_POST['items_purchased'],
        'receipt_total' => $_POST['receipt_total'],
    );

    $table_name = 'cogs';
    
    $result = $wpdb->insert($table_name, $data);

    $url = "/wordpress/cost-of-goods-sold";

    wp_redirect ( $url );
    exit ();
}

Now when I fill out the form, and click submit, the page re-loads itself. If I click refresh, the form does not reinsert the data.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement