简体   繁体   中英

ELSE statement doesn't return if while loop returns empty

I'm working on a script that checks to see if an email exists in the database barn_users , in order to reset a password. And if the email doesn't exists, the token/code is not generated and stored in the database. Everything works perfectly, until I enter an email that is not in the system. The else statement with the error "Could not find email in the system.", doesn't trigger. What am I doing wrong to not get that?

    $sql_1 = "SELECT * FROM password_reset WHERE email='$email'";
    $sql_2 = "SELECT * FROM barn_users WHERE email='$email'";

    $generate = mysqli_query($conn, $sql_1);
    $searchEmail = mysqli_query($conn, $sql_2);
    while($row = mysqli_fetch_array($searchEmail)) {
            if(mysqli_num_rows($searchEmail) > 0) {
                if (mysqli_num_rows($generate) > 1) {
            } else if (mysqli_num_rows($generate) < 1) {
                $sql = "INSERT INTO password_reset (code,email) VALUES ('$code','$email')";
            } else {
                $sql = "UPDATE password_reset SET code='$code' WHERE email='$email'";
            }   
            if ($conn->query($sql) == TRUE) {
                echo "Reset password has been emailed to you"; 
            } else {

            }
        } else {
            echo "Could not find email in the system.";
        } 
    }

Thank you @Bleach and @ivanivan for your comments. Both your answers helped out. Here's the working result. Making a variable false outside of the loop, gave me the answer I was looking for.

    $sql_1 = "SELECT * FROM password_reset WHERE email='$email'";
    $sql_2 = "SELECT * FROM barn_users WHERE email='$email'";

    $generate = mysqli_query($conn, $sql_1);
    $searchEmail = mysqli_query($conn, $sql_2);

    $found = false;

    while($row = mysqli_fetch_array($searchEmail)) {
        $found = true;
        if(mysqli_num_rows($searchEmail) > 0) {
            if (mysqli_num_rows($generate) > 1) {

            } else if (mysqli_num_rows($generate) < 1) {
                $sql = "INSERT INTO password_reset (code,email) VALUES ('$code','$email')";
            } else {
                $sql = "UPDATE password_reset SET code='$code' WHERE email='$email'";
            }   
            if ($conn->query($sql) == TRUE) {
                echo "Reset password has been emailed to you"; 
            } else {

            }
        } else {

        }
    }

    if ($found == false) {
        echo "Sorry, that email was not found in the system. Please try again.";
    }

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