Dan
Dan

Reputation: 9

PHP if else statement else gives blank screen

I have a problem with my if else statement near the bottom of the code.

If condition is true, it correctly echo logged in and username "super_user" but if condition is false I get a blank screen, it does not echo my fail message "nope"

"super user" and "password" get passed from an html input form in a previous page

I am not sure what I got wrong here, I am really new to 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"; 
        }
    }

}
?>

I was trying to make a simple login system that would set a session and redirect back to the home page using something like :

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

But before I even do that I wanted to just echo the username "super_user" to see if my if else statement was working.

Upvotes: 0

Views: 897

Answers (2)

Laurence
Laurence

Reputation: 60068

The problem is if you run a false query, you will never enter the while loop (Because it will not match a user/password in the first place, so your sql query will not return any results/rows).

So your code skips the while loop.... and then just ends - hence a 'white' page.

Just add a message at the end:

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';
}

Upvotes: 0

Alexander Gelbukh
Alexander Gelbukh

Reputation: 2240

Your SQL query retrieves all rows with the given username and password. Either there is (exactly) one or there is none. So your if() will be always true if there is one, and will never execute if there is none because your while will be executed 0 times.

Rather you can use

$found = 0;

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

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

or simpler:

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

Upvotes: 0

Related Questions