【问题标题】:PHP if else statement else gives blank screenPHP if else 语句 else 给出空白屏幕
【发布时间】:2014-09-14 13:58:18
【问题描述】:

我在代码底部附近的 if else 语句有问题。

如果条件为真,它正确地回显登录和用户名“super_user”,但如果条件为假,我得到一个空白屏幕,它不会回显我的失败消息“nope”

“超级用户”和“密码”从上一页的 html 输入表单中传递

我不确定我在这里做错了什么,我真的是 PHP 新手。

<?php 
session_start(); 
if ($_POST['Submit2']) {  
    $super_user= $_POST['super_user'];
    $password= $_POST['password']; 

    $db = new mysqli('*******', '******', '*******', '******');

    if($db->connect_errno > 0){
        die('Unable to connect to database [' . $db->connect_error . ']');
    }

    $sql = <<<SQL
    SELECT *
    FROM `admin`
    WHERE password='$password' AND  super_user='$super_user'
    SQL;

    if(!$result = $db->query($sql)){
        die('There was an error running the query [' . $db->error . ']');
    }


    while($row = $result->fetch_assoc()){

        if  (($super_user == $row['super_user'] && $password == $row['password'] )){ 
            echo "logged in "; 
            echo "<br>"; 
            echo $row['super_user']; 
        }
        else
        {
            echo "nope"; 
        }
    }

}
?>

我正在尝试制作一个简单的登录系统,该系统将设置会话并使用以下内容重定向回主页:

$_SESSION['loggedin'] = $super_user;
header("Location:index.php");
exit;

但在我这样做之前,我只想回显用户名“super_user”,看看我的 if else 语句是否有效。

【问题讨论】:

标签: php if-statement


【解决方案1】:

问题是如果你运行一个错误的查询,你永远不会进入while循环(因为它首先不会匹配用户/密码,所以你的sql查询不会返回任何结果/行)。

所以你的代码跳过了 while 循环......然后就结束了 - 因此是一个“白色”页面。

只需在末尾添加一条消息:

if  ($result->rowCount > 0)
{
    while($row = $result->fetch_assoc()){

        if  (($super_user == $row['super_user'] && $password == $row['password'] )){ 
            echo "logged in "; 
            echo "<br>"; 
            echo $row['super_user']; 
        }
        else
        {
            echo "nope"; 
        }
    }
}
else
{
    echo 'no matching user found';
}

【讨论】:

  • 这将始终回显没有找到匹配的用户,无论他是否被找到(以及如果找到的附加信息)。如果我错了,请纠正我,如果是这样,我会喝双份浓缩咖啡。
  • 是的 - 我想我需要双份浓缩咖啡:)
  • 你太棒了! ;) 正如我所说,我对此并不陌生,但这个例子确实有效。
【解决方案2】:

您的 SQL 查询检索具有给定用户名和密码的所有行。要么有(确切地)一个,要么没有。因此,如果有一个 if() 将始终为真,如果没有则永远不会执行,因为您的 while 将被执行 0 次。

你可以使用

$found = 0;

while ($row = $result->fetch_assoc())
{
    $found = 1;
}

if ($found)
    echo "Logged in";
else
    echo "nope";

或更简单:

if ($result->fetch_assoc())
    echo "Logged in";
else
    echo "nope";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2017-02-05
    • 2011-05-18
    相关资源
    最近更新 更多