简体   繁体   中英

How to show one echo out of two from my if statement using PHP?

I'm having a school project and I'm making a login system where you can login with email or username. But I'm having a problem with showing the correct echo that the email or username is incorrect.

Here's my code:

if(strpos($emailOrUsername, "@")){
    $query = $dbh->prepare('SELECT * FROM register WHERE email = ?');
    $query->execute(array($emailOrUsername));
}

        if($query->rowCount() == 0){
                echo('Email is incorrect');

             }


if($emailOrUsername){
    $query2 = $dbh->prepare('SELECT * FROM register WHERE username = ?');
    $query2->execute(array($emailOrUsername));
}
        if($query2->rowCount() == 0){
                echo('Gebruikersnaam bestaat niet');

             }

Now I want to show only one echo. Because if you fill in the wrong email and username it's going to show both echo's and I want it to show only one.

You don't need to. Query for both in one query and if no rows are returned then you answer that "No such user", otherwise you are helping the hacker one step closer to deduct which usernames or emails are correct or not.

Addition:

Don't reveal if the username/email or password was incorrect. Just give a general error message.

I think you have to change

if(strpos($emailOrUsername, "@"))

to

if(strpos($emailOrUsername, "@") !==false)

and

if($emailOrUsername)

to

elseif($emailOrUsername) or elseif(!empty($emailOrUsername))

Although there is plenty of room to improvise your query, yet I have refined it to fit your needs as of now.

if(strpos($emailOrUsername, "@")){
    $query = $dbh->prepare('SELECT * FROM register WHERE email = ?');
    $query->execute(array($emailOrUsername));

    if($query->rowCount() == 0){
        echo('Email is incorrect');
    }
}
else {
    $query2 = $dbh->prepare('SELECT * FROM register WHERE username = ?');
    $query2->execute(array($emailOrUsername));

    if($query2->rowCount() == 0){
        echo('Gebruikersnaam bestaat niet');
    }
}

You don't need to have multiple if conditions when you can achieve this in one if else block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM