4

Hi I am new in php and started learning. I am trying to increment variable value with 1 when submit button is pressed.

My Code:

<?php
    $i=0;
    if($_POST['submit']){
        echo $i+1;  
    }
?>

Thanks

Manan
  • 1,197
  • 4
  • 15
  • 25
  • 2
    You need to store that variable somewhere, eg. File, Database or even Session. What you're doing will always show `1`. – vee Jul 05 '13 at 17:53
  • 1
    After this script is run, the variable $i is freed in memory (aka it's gone). The next time you execute the script, PHP has no idea what $i is until you set $i=0. So when you click submit it will always echo 1. – Caleb Taylor Jul 05 '13 at 18:00

4 Answers4

5

You're variable $i should be stored in session for example, so it won't lost its value when you submit the form. (You can check this answer Is PHP or PHP based web framework stateful or stateless?)

Also when your script is executed, the first thing you do is $i = 0; so whenever you execute it, you reinitialize the variable to 0.

session_start();

// if your variable is not yet defined, you assigned it with 0
if (isset($_SESSION['myVariable']))
{
    $_SESSION['myVariable'] = 0;
}

if($_POST['submit'])
{
    echo $_SESSION['myVariable'] +1;  
}
Community
  • 1
  • 1
Anas
  • 5,622
  • 5
  • 39
  • 71
2
<?php
session_start();

    if($_POST['submit']){
        $_SESSION['i'] = isset($_SESSION['i']) ? ++$_SESSION['i'] : 0;
        echo $_SESSION['i'];
    }
?>

This will remember the last value between pages

Simón Urzúa
  • 1,556
  • 2
  • 11
  • 16
1
var_dump($IsPost = !strcasecmp($_SERVER['REQUEST_METHOD'], 'POST'));

^ tells you if it's a post.

echo ++$i;

^ increments $I and then prints $I

echo $i++;

^ prints $I and then increments $I

empty($_POST['submit']); // or isset($_POST['submit']);

^ tells you if ['submit'] exists in $_POST without notices.

CodeAngry
  • 12,760
  • 3
  • 50
  • 57
1
<?php
if(!isset($_SESSION['i'])) $_SESSION['i'] = 0;
if(isset($_POST['submit'])){
    $_SESSION['i']++;
}
echo $_SESSION['i'];
?>
iTom
  • 281
  • 1
  • 5