0

I have a mail counter that gets incremented when an email is successfully sent. This mail count is visible in the email body. The problem arises when two forms are submitted at almost the same time. When this happens the email is sent to different users containing the same mail count, example 10 and 10, whereas it should be 10 and 11.

Initial code from here https://sevenspark.com/tutorials/how-to-create-a-counter-for-contact-form-7

#this code block is inserted in the email through shortcode
function RC_counter_func() {
    $val2 = date( "Y" ) . '-' . zeroise( get_option( 'RC_COUNTER', 0 ) + 1, 5 ); //Increment the current count  
    return $val2;
}
add_shortcode( 'RC_COUNTER', 'RC_counter_func' );

// Action performed when the mail is actually sent by CF7
function cf7dtx_increment_mail_counter( $WPCF7_ContactForm ) {

    #retrieve the details of the form/post
    $wpcf7 = WPCF7_ContactForm::get_current();
    $submission = WPCF7_Submission::get_instance();
    $form_id = $WPCF7_ContactForm->id();

    if ( $submission && $form_id === 988 || $form_id === 1584 )   {
        $val2 = zeroise( get_option( 'RC_COUNTER', 0 ) + 1, 5 ); //Increment the current count
        update_option( 'RC_COUNTER', $val2 ); //Update the settings with the new count
    }
}
add_action( 'wpcf7_mail_sent', 'cf7dtx_increment_mail_counter' );

Any ideas on how to prevent duplication would be much appreciated! When submitting forms one after the other there is no issue, and the number is being incremented correctly in the DB, but not in the email.

John Montgomery
  • 6,739
  • 9
  • 52
  • 68
FED
  • 19
  • 2

1 Answers1

0

What about just generating a random string of a little bit of length (say 6 characters) and appending that to the Counter ID? To make the value unique. The chance of those two colliding can be probabilistically small.

You can use this method to generate a random string:

PHP random string generator

Absent that - you'll need to find a way to make your read/update DB operation run in a transaction where the counter is a serially incrementing integer.

Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
  • Thanks @cody, but I have no choice, these are the requirements. To your second point, I am attempting that but I believe it's in the timing when I'm grabbing the serial number, I need to grab the serial number between pressing the submit button but before the email sends. The timing or logic I'm using is not working out. Example Form 1 grabs serial #10, Form 2 grabs #10 as well since Form 1 has not yet finished processing and incrementing the serial count..this cause two emails to be sent out with serial #10 – FED Feb 05 '19 at 15:30
  • Yes @FED which is why you need to add some fuzz to the serial number by virtue of generating some random string gibberish. – Cody Caughlan Feb 06 '19 at 17:34