在if / else语句中计数

时间:2014-11-12 14:25:13

标签: php jquery mysql database counter

我有一个登录页面,要求用户输入代码。我想计算用户输入错误代码的次数,如果超过3次,则显示一个页面告诉他们重新启动进程,但我的计数器只输出1,即使我多次键入错误的代码。

<div class="container">


<div class="alert alert-success" role="alert" align="center">
    <p>A code has been sent to your email</p>
    <p>Please consult your email to proceed with the login</p>
</div>

<form class="form-signin"  method="post">
    <h2 class="form-signin-heading">Enter code</h2>
    <input type="hidden" name="partnerEmail" value="<?php echo $_POST['partnerEmail']; ?>">
    <input class="form-control" type="text" name="partnerCode" placeholder="Code">
    <button class="btn btn-lg btn-primary btn-block" type="submit">Accept</button>

</form>

</div> <!-- /container -->

<?phpsession_start();echo $_SESSION['partnerEmail'];?>

<div class="container">

<?php
include_once "conn.php";

$partnerCode = $_POST['partnerCode'];
$partnerEmail = $_SESSION['partnerEmail'];

$sql = "SELECT * FROM partners WHERE partner_email='$partnerEmail' AND 
partner_login_code='$partnerCode' AND partner_active ='yes'";


$counter = 0;
echo $counter;

$result = $conn->query($sql);

if (mysqli_num_rows($result)>0){
    echo '<div class="alert alert-success" role="alert" align="center">
          <p>Congratz - You logged in successfully!</p>
          </div>';


}
else
{
    echo '<div class="alert alert-danger" role="alert" align="center">
          <p>ERROR - Please consult your email for the correct code!</p>
          </div>';

    $counter ++;
    echo $counter;

?> <script> $(".alert").effect("shake");</script> <?php
}

echo $counter;
?>

3 个答案:

答案 0 :(得分:1)

您需要存储$ counter值。

首先说道:

$counter = 0;
echo $counter;

它可以转换为:

if(isset($_SESSION['counter']) && $_SESSION['counter'] > 0){
 $counter = $_SESSION['counter'];
}else{
 $counter = 0;
}

的部分
$counter ++;

成为

$counter ++;
$_SESSION['counter'] = $counter;

然后你可以在其他页面上访问它(只要它们是php并且可以访问会话变量)。

答案 1 :(得分:1)

Php是无国籍的。每次加载页面时都会覆盖计数器。 而是将计数器保存到会话中:

//$counter = 0; this is overwritting, replace with:
$_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter'] : 0;
//assigned by reference, changes to $counter will change $_SESSION['counter'] also
$counter = &$_SESSION['counter'];

除了上述内容之外,您还可以在输出html后开始会话。这不起作用,因为启动会话需要发送http标头,必须在发送http响应之前完成(例如html)

答案 2 :(得分:0)

U可以在$ _SESSION数组中保存一个计数器,只需在用户输入错误代码时增加该值。达到某个值后,您可以在代码中执行不同的操作。