Reputation: 470
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.
Upvotes: 0
Views: 1649
Reputation: 2104
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
Upvotes: 0
Reputation: 24425
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
$counter
if the button data exists, from zero to oneWhat 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'];
?>
Upvotes: 3