问题描述
我试图创建一个变量来存储点击的按钮数。不幸的是我得到这个错误:
未定义变量:counter
这是我的代码:
if($ _SERVER [REQUEST_METHOD] ==POST){
$ counter = isset($ _ POST ['counter'])? $ _POST ['counter']:0;
if(isset($ _ POST [button])){
$ counter ++;
echo $ counter;
它是一种形式:
< form action =<?php echo htmlspecialchars($ _ SERVER [PHP_SELF]);?> method = post>
< input type =submitname =buttonvalue =Submit>
< input type =hiddenname =countervalue =<?php print $ counter;?>; />
< / form>
有人知道我做错了什么吗?
代码中没有错误。它在我的最后工作。您需要检查两点:
-
PHP代码应该在HTML上面,HTML代码会在PHP代码之后出现。因此,
$ counter
变量将被初始化。 - PHP和HTML代码应该位于同一页面上。 >因此,行
PHP code should be above on HTML, HTML code will come after PHP code. So that
$counter
variable will be initialized.PHP and HTML code should be on same page.
$ counter = isset($ _ POST ['counter'])? $ _POST ['counter']:0;
不应该在if块中。可以肯定的是,**将此行作为PHP文件的第一行。然后只有 $ counter
变量可用于整个页面。 I tried to create a variable to store a count of button clicked. Unfortunetlly i get this error:
Undefined variable: counter
It's my code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
if(isset($_POST["button"])){
$counter++;
echo $counter;
}
}
And it's a form:
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = post>
<input type = "submit" name = "button" value = "Submit" >
<input type = "hidden" name = "counter" value = "<?php print $counter; ?>"; />
</form>
Anybody know what i'm doing wrong?
There is no error in your code. Its working at my end. You need to check two points:
As OP edited the question: So, the line $counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
should not be in if-block. To be sure, ** Make this line as a first line of PHP file. Then only $counter
variable will be available for whole page.
这篇关于按钮点击计数器[PHP]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!