在php中只初始化一次变量 [英] 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.
我的 index.php
代码是这样的:
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
}
我的index2.php
是:
<?php $_SESSION['session_variables_updated'] = 1; ?>
<a href="index.php">back</a>
但是由于变量再次被初始化,所以每次都设置为0.关于这个问题的任何指导?
But since the variable is again being initialized, it is set to 0 every time. Any guidance on this problem?
推荐答案
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
这篇关于在php中只初始化一次变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!