按钮点击计数器[PHP] [英] Button click counter [PHP]

查看:410
本文介绍了按钮点击计数器[PHP]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个变量来存储点击的按钮数。不幸的是我得到这个错误:

 未定义变量: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>

有人知道我做错了什么吗?

解决方案

代码中没有错误。它在我的最后工作。您需要检查两点:


  1. PHP代码应该在HTML上面,HTML代码会在PHP代码之后出现。因此, $ counter 变量将被初始化。

  2. PHP和HTML代码应该位于同一页面上。
  3. >因此,行 $ 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:

    1. PHP code should be above on HTML, HTML code will come after PHP code. So that $counter variable will be initialized.

    2. PHP and HTML code should be on same page.


    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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆