php 提交时php将变量值增加1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17494444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php increment variable value with 1 when submit
提问by Manan
Hi I am new in php and started learning. I am trying to increment variable value with 1when submit button is pressed.
嗨,我是 php 新手并开始学习。我试图在按下提交按钮时将变量值增加1。
My Code:
我的代码:
<?php
$i=0;
if($_POST['submit']){
echo $i+1;
}
?>
Thanks
谢谢
回答by Anas
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?)
例如,您的变量 $i 应该存储在会话中,因此在您提交表单时它不会丢失其值。(您可以查看此答案是 PHP 还是基于 PHP 的 Web 框架是有状态的还是无状态的?)
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.
同样,当你的脚本被执行时,你做的第一件事就是$i = 0;
每当你执行它时,你将变量重新初始化为 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;
}
回答by Simón Internacional
<?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
这将记住页面之间的最后一个值
回答by CodeAngry
var_dump($IsPost = !strcasecmp($_SERVER['REQUEST_METHOD'], 'POST'));
^ tells you if it's a post.
^ 告诉你它是否是一个帖子。
echo ++$i;
^ increments $I
and then prints $I
^ 递增$I
然后打印$I
echo $i++;
^ prints $I
and then increments $I
^ 打印$I
然后递增$I
empty($_POST['submit']); // or isset($_POST['submit']);
^ tells you if ['submit']
exists in $_POST
without notices.
^ 告诉您是否['submit']
存在,$_POST
而无需通知。
回答by iTom
<?php
if(!isset($_SESSION['i'])) $_SESSION['i'] = 0;
if(isset($_POST['submit'])){
$_SESSION['i']++;
}
echo $_SESSION['i'];
?>