2015-03-19 39 views
0

我試圖創建一個點擊計數,每次點擊按鈕都會調用一個incrementClickCount()函數,該函數將變量$ count = 0設置爲靜態,增加$ count變量並顯示它。我不明白爲什麼它不起作用。php/html:點擊計數器不起作用

<html> 
<head> 
    <title>Click Counter</title> 
    <?php 
     if(isset($_POST['clicks'])){ 
      incrementClickCount(); 
     } 

     function incrementClickCount(){ 
      static $count=0; 
      $count++; 
      echo $count . " and counting..."; 
     } 
    ?> 
</head> 
<body> 
    <form name="form1" method="POST" action="<?php $_SERVER['PHP_SELF']; ?>"> 
     <input type="submit" name="clicks" value="click me!"> 
    </form> 
</body> 

+2

靜沒有保持跨請求,您需要保存計數器的地方 – Andrey 2015-03-19 10:38:55

+0

好吧,我會盡量會議來代替。謝謝! – 2015-03-19 11:05:01

回答

0

在你的代碼,當函數incrementClickCount()被調用時,你$計數器總是被設置爲0,遞增......你需要一次申報您$計數器變量保存在某個地方,以會議爲例

+0

我還不知道會話,但我會檢查出來並測試它。謝謝! – 2015-03-19 11:06:36

+0

不客氣,我希望它有幫助。如果你有問題,我願意幫助你;) – zdeniiik 2015-03-19 13:41:43

+0

謝謝!我嘗試會話,並且正常工作。我將下面的代碼放在其他需要幫助的人身上。 – 2015-03-19 13:54:11

0

對於那些正在與同樣問題掙扎的人。這是我的代碼修復。非常感謝那些幫助過我的人。 Zdenek Leitkep和Andrey建議使用會話來代替。 我發現如何在這裏使用它:http://php.net/manual/en/session.examples.basic.php

<html> 
<head> 
    <title>Sessions: Click Counter</title> 
    <?php 
     session_start(); 
     if(isset($_POST['clicks'])){ 
      incrementClickCount(); 
     } 

     function incrementClickCount(){ 
      if (!isset($_SESSION['count'])) { 
       $_SESSION['count'] = 0; 
      }else{ 
       $_SESSION['count']++; 
       print $_SESSION['count']; 
      } 
     } 
    ?> 
</head> 
<body> 
    <form name="form1" method="POST" action="<?php $_SERVER['PHP_SELF'];?>"> 
     <input type="submit" name="clicks" value="click me!"> 
    </form> 
</body> 
</html>