简体   繁体   中英

Initialize the variable only once in php

I am stuck in a problem where I need to initialize the session variable only once. When he hits submit and comes back to the same page, the variable value should be changed.

My index.php code is something like this:

<?php
session_start();
$_SESSION['session_variables_updated'] = 0;
?>
<form name="" method="post" action="index2.php">
    <input type="submit" value="Submit" name="Submit">
</form>

if ($_SESSION['session_variables_updated'] == 1) {
    //do something
}

My index2.php is:

<?php $_SESSION['session_variables_updated'] = 1; ?>
<a href="index.php">back</a>

But since the variable is again being initialized, it is set to 0 every time. Any guidance on this problem?

Please Do change one index2.php file

you have to add after php start and before define variable

session_start();

Hope you got idea after see this.

index.php

<?php
session_start();
if(!isset($_SESSION['session_variables_updated'])){
    $_SESSION['session_variables_updated']=0;
}
?>
<form name="" method="post" action="index2.php">
    <input type="submit" value="Submit" name="Submit">
</form>
<?php
if ($_SESSION['session_variables_updated'] ==1){
//do something
}


?>

Please try this. What i have done here, I just checked the session variable is allocated or setted or not if it is not available the i assign the zero to that . otherwise i allow it to perform another actions.

in your 2nd page you should start session before doing somethings with sessions

<?php
session_start();
$_SESSION['session_variables_updated'] = 1;
?>
<a href="index.php"> back </a>

Defenitly this will work pleaase have a try. this is working in my case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM