0

I am new to php and I am confused with the following problem: I have a button called BtnAdd wich is surrounded with a form tag(POST)

Now I am trying to do +1 with each click. This is my code:

$counter = 0;

if (isset($_POST['BtnAdd'])) 
{ 
 $counter++;
}

echo $counter     

My problem is that each time I click the button it only returns 1 but it never goes up

If you have any idea please post.

3
  • Are you sure this is the code you're using ? Your code should either return 0 or 3. And please don't forget ; Commented Dec 1, 2013 at 19:06
  • Could you please post a more complete version of your code? The example you provided should be obviously working, that way. Commented Dec 1, 2013 at 19:06
  • I am sorry, my mistake! the problem is that the counter doesn't goes up each time I click on the button Commented Dec 1, 2013 at 19:09

2 Answers 2

3

You need to store the reference to "3" somewhere, it is not a magic number and I presume it's not going to be hard coded in. Your current logic flow is this

  • click button on form
  • script processing form assigns variable to zero
  • script increments $counter if the button data exists, from zero to one

What you should be doing is replacing $counter with a number read from somewhere (session, file, database).

Here are some storage options for it:

Here's a quick example of how to do it with sessions:

<?php

session_start();

if(!isset($_SESSION['counter']))
    $_SESSION['counter'] = 0; // create variable if doesn't exist

if(isset($_POST['BtnAdd'])) {
    $_SESSION['counter']++;
}

echo $_SESSION['counter'];

?>
  • this will at least increment your counter while your browser window is still open.
Sign up to request clarification or add additional context in comments.

Comments

0

when you are submitting the form, in the processing page before the counter, you are initialising the counter to the value 0 everytime you post.your counter value is not getting stored anywhere.you have to store the present value so that incrment it next time

session_start();
$counter = 0;
if(isset($_SESSION['count'])){
    $counter=$_SESSION['count'];
}


if (isset($_POST['BtnAdd'])) 
{ 
   $counter++;
   $_SESSION['count']=$counter;
}

echo $counter 

here it is stored in session and u can access stored count value from session

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.