[Solved] Page count issue updating DB twice when form submits

Hi all

example.php
I have a page count which updates the DB every time this page is viewed/loaded:

$db->query("UPDATE `click_counter` SET counter = counter + 1");

And further down this page I have a form for collecting data which validates the data and once everything passes the validation and the submit button this clicked:

if (isset($_POST['submit'])) {
...
$db->insert('confirmed_details', $data);

Everything works ok.
But, the form posts to itself and re-sends the page resulting in the page counter adding another count. If the page is viewed and also has the form submitted I get two counts instead of one.

Is there a way of adding some sort of time threshold so if the page re-submitted in about 2 minutes the count won’t record but the forms data still gets sent. Maybe there is an easier way?

I know I can probably have a separate file though hoping to keep everything on the one page.

Thanks for your suggestions,
Barry

Without knowing the greater architecture of your project this is what I’d try. After the isset($_POST) is called I’d set a flag, probably a constant. Then check to see if that flag was set before incrementing the click counter, and not do the increment when it’s set. For this to work the code snippet you presented second must echo first.

As a rule of thumb, click counts should be among the last things your program does for this reason.

Cool thanks Michael

The idea is to record the visit/count rate, which then compares to the actually registrations, sort of a bounce rate indicated, tracking how many continued and filled out the form.

I’m no PHP guru and haven’t used flags before, if you could advise further that would be great.

I’m using the Zend FW and have some basic validation which I’ve added myself.
Here is the full code, minimised the validation fields for easy viewing.

// Create connection
$config = array
  (
  'host' => $DB_HOST,
  'username' => $DB_USER,
  'password' => $DB_PASSWD,
  'dbname' => $DB_REPLDB
);

$db = new Zend_Db_Adapter_Pdo_Mysql($config);
$db->query("UPDATE `click_counter` SET counter = counter + 1"); //counter

$first_name         = '';
$surname            = '';

if (isset($_POST['submit'])) //check for name of your submit button
{
  if (isset($_POST['first_name'])) {$first_name = trim(stripslashes($_POST['first_name']));}
  if (isset($_POST['surname'])) {$surname = trim(stripslashes($_POST['surname']));}
  
  if (strlen($first_name) == 0) {$s_error_message .= "X Please enter a valid first name<br>";}
  if (strlen($surname) == 0) {$s_error_message .= "X Please enter a valid surname<br>";}
  
  if (strlen($s_error_message) == 0)
  {
  	  $data = array
    (
        'first_name' => $first_name,
        'surname' =>  $surname
    );
  	  		  
    $db->insert('confirmed_details', $data);
      
      $to="test@example.com";
      $message = "Sender: " 
          . $first_name . ' ' 
          . $surname;
      $subject = "Sign me up!"; 
                
      if (mail($to, $subject, $message, 'From: ' . $first_name)) {header('Location: https://test.example.com/thanks.php');}
      else {print('There was a problem sending the mail.');}
  }
}

<form method="post" action="">

Is this something we can add easily with the code above?
Any advice examples much appreciated.

Thanks, Barry

Yes, the issue is that it re-loads the page when you submit the form, so you just need to check whether or not the form is loading “naturally”, or as a result of your user submitting the form. Something like this:

// Create connection
$config = array
  (
  'host' => $DB_HOST,
  'username' => $DB_USER,
  'password' => $DB_PASSWD,
  'dbname' => $DB_REPLDB
);

$postresult = false; // create a var and assume it's false
if (isset($_POST['submit'])) $postresult = true; // unless we're posting, then set it to true

if (!(postersult)) { // we're not dealing with the form submission, so increment counter
  $db = new Zend_Db_Adapter_Pdo_Mysql($config);
  $db->query("UPDATE `click_counter` SET counter = counter + 1"); //counter
  }

$first_name         = '';
$surname            = '';

if ($postresult) //  we are dealing with the form submission
{
  if (isset($_POST['first_name'])) {$first_name = trim(stripslashes($_POST['first_name']));}
  if (isset($_POST['surname'])) {$surname = trim(stripslashes($_POST['surname']));}

  if (strlen($first_name) == 0) {$s_error_message .= "X Please enter a valid first name<br>";}
  if (strlen($surname) == 0) {$s_error_message .= "X Please enter a valid surname<br>";}

  if (strlen($s_error_message) == 0)
  {
  	  $data = array
    (
        'first_name' => $first_name,
        'surname' =>  $surname
    );

    $db->insert('confirmed_details', $data);

      $to="test@example.com";
      $message = "Sender: " 
          . $first_name . ' ' 
          . $surname;
      $subject = "Sign me up!"; 

      if (mail($to, $subject, $message, 'From: ' . $first_name)) {header('Location: https://test.example.com/thanks.php');}
      else {print('There was a problem sending the mail.');}
  }
}

<form method="post" action="">

Thanks alot droopsnoot.

Just tried to update this, first I got the error, also was a small spelling.

Use of undefined constant postresult - assumed 'postresult'

Nothing changed after the spelling update so I added $:

if (!($postresult)) {

Is this correct, no errors now.

Though now, when I submitted the form:

Undefined variable: db 
Fatal error: Call to a member function insert() on a non-object in... line 111

Line 111 is:

$db->insert('confirmed_details', $data);

Can you see what’s wrong?

Thanks, Barry

I think I’ve fixed it, I needed to move the connection adapter above, seems to be working good I submitted the form and it doesn’t update the counter table :slight_smile:

$db = new Zend_Db_Adapter_Pdo_Mysql($config);

$postresult = false; // create a var and assume it's false
if (isset($_POST['submit'])) $postresult = true; // unless we're posting, then set it to true
if (!($postresult)) { // we're not dealing with the form submission, so increment counter

$db->query("UPDATE `click_counter` SET counter = counter + 1");

Just one problem, it seems to be updating by 2 every time the page loads now, maybe this is due to my dev environment. Can you see a problem in the code that would make this now update by 2 instead of 1?

Thanks for your assistance, and thanks for the comments next to the code previously, real helps.

Barry

Or… Just an “else” on your if… If the form data is present process it, else count page view

Sorry, my mistake, I’m always forgetting to stick the $ sign at the start of variable names, and spelling them badly by the look of it too. As you found, that should have read $postresult. You’re quite correct about the other part - I’d put the database connection code into the conditional for whether we’re dealing with the submission or not, and only briefly scanned the rest of the code, didn’t notice that the mail section also updated the database.

I can’t think why it would add two to the counter. Is it updating by 2, or is it updating by one twice for some reason? Can you post the code as it stands now?

Cool, so I am learning something ha

It was updating by 2. Everything is fixed now! Like I mentioned, I think it had something to do with the dev environment, I deployed things today on the production server and everything works great, thank you, and thanks fro sharing the knowledge :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.