按钮计数器的PHP代码

时间:2014-12-15 17:45:55

标签: php counter

我试图运行一个计算按钮点击次数的PHP代码。它增加到1然后它不计数。这是我的代码:

<?php
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 = "submit" name = "button" value = "vote" >
</form>

我不是php专家所以任何人都可以告诉我哪里出错了?

由于

3 个答案:

答案 0 :(得分:0)

使用这个php:

<?php
if(isset($_POST["button"])){
    $counter++;
    echo counter;
}
?>

此外,将其用于开场<form>元素

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

答案 1 :(得分:0)

试试这个:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $counter = isset($_POST['counter']) ? $_POST['counter'] : 0;
  if(isset($_POST["button"])){
    $counter++;
    echo $counter;
   }
}
?>
<form action = "<?php echo $_SERVER["PHP_SELF"]; ?>" method = post>
  <input type = "hidden" name = "counter" value = "<?php echo $counter; ?>" />
  <input type = "submit" name = "button" value = "vote" />
</form>

答案 2 :(得分:0)

将计数存储在会话中。请注意,这会为每个用户存储单独的计数。如果您想要在所有用户之间共享一个计数,那么您需要将其存储在数据库中。

<?php
// Start the session
session_start();
// Make sure a session variable exists
if ( !isset($_SESSION['count']) ) {
    $_SESSION['count'] = 0;
}
// Check to see if a vote has been submitted
$vote = isset($_POST['button']) ? $_POST['button'] : false;
if ( $vote ) {
    // Increment the vote
    $_SESSION['count']++;
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
    <input type="submit" name="button" value="Vote">
</form>