Home > Blockchain >  PHP form data reinserting input into Wordpress database each time page is refreshed
PHP form data reinserting input into Wordpress database each time page is refreshed

Time:03-15

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?

CodePudding user response:

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.

CodePudding user response:

Similarly to all the headers functions, wp_redirect can only be used before any output of the page.

See this answer for additional information.

Move wp_redirect before any output is done, for example where you manage your POST data.

Furthermore, as presented in the official documentation wp_redirect doesn't exit automatically. You need to put an exit(); after it.

if ( wp_redirect( $url ) ) {
    exit;
}
  • Related