Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
444 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...