如果PHP工作不正常,则多个其他


Multiple else if not working correctly PHP

我的登录脚本有问题。其余的都很好,但这里发生了一些奇怪的事情。问题是,即使$IPCHK返回true,elseif函数也不会执行。它只在我将$IPCHK设置为jibberish时执行。任何帮助都会很棒。提前感谢

if ($Numrows == 0)
{
    if ($Fail >= 3)
    {
        $Connection = connectToDb();
        //return true, false,pending
        $IPCHK = checkIP();
        $IPCHK = true; //forcing it to be true and still broke
        //If no ip id there
        if($IPCHK == false)
        {
            $IP = getIP();
            $Query = "INSERT INTO ip VALUES ('','$IP',Now())";
            mysqli_query($Connection, $Query)
                or die(error(mysqli_error($Connection)));
            echo "You have failed to login too many times";
            echo "<br />Please <a href='login.php'>try again</a> later.";
            $Lock = true;
        }
        //If ip is there but timer is not up
        elseif ($IPCHK == 'pending')
        {
            echo "You have failed to login too many times";
            echo "<br />Please <a href='login.php'>try again</a> later.";
            $Lock = true;
        }
        //Timers Up
        elseif ($IPCHK == true) //here does not execute when it returns true
        {
            $_SESSION['FailedLogin'] = 0;
            $Lock = false;
        }
        else
        {
            error("End of if check");
        }
    }
    else
    {
        $Fail = 3 - $Fail;
        $_SESSION['FailedLogin'] = $_SESSION['FailedLogin'] + 1;
        $Error = $Error."<br />You have ".$Fail." attempts remaining";
    }
}

在您的条件下,您有

 elseif ($IPCHK == 'pending')

然后

elseif ($IPCHK == true)

另一个永远不会执行,因为$IPCHK=="挂起"也意味着$IPCHK===true如果你想执行你的第二个,你必须把第二个条件改成类似的条件

elseif($IPCHK == 'done')

或者像这个一样简单地使用===

elseif($IPCHK === 'pending')

然后

elseif($IPCHK === true)

Lamari Alaa是正确的,关于类型杂耍的相关文档条目可以帮助理解原因。

以下脚本输出:boolean = string:

$test = true;
if( $test == 'pending' ) {
    echo 'boolean = string';
} else if ( $test ) {
   echo 'boolean != string';
}

这是因为字符串"pending"在与布尔值true进行比较之前被强制转换为布尔值。由于它的计算结果为true,因此采用第一个条件。考虑将== 'pending'替换为=== 'pending'