Jump to content

Stop Variable Incrementing


virken

Recommended Posts

Thanks to those who helped previously - you guys are awesome!

One more question... I need to increment a session variable but only on form submission. Using the code below, my variable gets incremented every time the page loads. How can I make a variable incrementing only when a form is submitted and not during page refreshes and back navigation?


<input name="total" type="hidden" value=" <?php $_SESSION['total']++;?> ">
Link to comment
https://forums.phpfreaks.com/topic/31308-stop-variable-incrementing/
Share on other sites

if you have a submit button give it a name, like submit then just check if it has been pressed.

[code=php:0]
<?php
if(isset($_POST['submit'])){
echo "<input name='total' type='hidden' value='".$_SESSION['total']++."'>";
}
?>
<input type="text" name="afield"><br>
<input type="submit" name="submit" value="go">
[/code]

of course thats just an example...
hmm...  please take a look at this; tried to implement your suggestion but must have gone off-track...

<?php session_start(); if ( ! session_is_registered( $_SESSION['total']) ) {$_SESSION['total'] = 0; $total = $_POST['total'];} ?>
<html>
Increment Test

<?php echo "Pre-increment value of total = ", $_SESSION['total']; ?>

<form name="form1" method="post" action= "<?php $_SERVER['PHP_SELF']?>">

<input type="submit" name="Submit" value="Submit">

<?php if(isset($_POST['submit'])){
  echo "<input name='total' type='hidden' value='".$_SESSION['total']++."'>";
  }
?>
</form>

<?php echo "Post-increment value of total = ", $_SESSION['total']; ?>
</html>
thank you for helping me clean up the syntax - unfortunately the original problem remains. Whenever you REFRESH the page, the variable continues to increment. I need to prevent the increment unless the user has actually submitted the form - any other ideas???

<?php session_start();
if ( ! (isset( $_SESSION['total']) )) { $_SESSION['total'] = 0; $total = $_POST['total']; }?>

<html>
Increment Test

<?php echo "Pre-increment value of total = ", $_SESSION['total']; ?>

<form name="form1" method="post" action= "<?php $_SERVER['PHP_SELF']?>">

<input type="submit" name="Submit" value="Submit">

<?php if(isset($_POST['Submit'])){
  echo "<input name='total' type='hidden' value='".$_SESSION['total']++."'>";
  }
?>
</form>

<?php echo "Post-increment value of total = ", $_SESSION['total']; ?>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.