user2871811
user2871811

Reputation: 470

Php button click

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

Answers (2)

Bhadra
Bhadra

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

scrowler
scrowler

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

  • 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.

Upvotes: 3

Related Questions