如果while循环返回空,则ELSE语句不返回

时间:2018-06-24 02:06:25

标签: php mysql mysqli php-7

我正在处理一个脚本,该脚本检查以查看数据库barn_users中是否存在电子邮件,以便重置密码。而且,如果电子邮件不存在,则不会生成令牌/代码并将其存储在数据库中。一切正常,直到我输入系统中未包含的电子邮件。错误为“在系统中找不到电子邮件”的else语句不会触发。我做错了不明白吗?

    $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.";
        } 
    }

1 个答案:

答案 0 :(得分:2)

感谢@Bleach和@ivanivan的评论。您的答案都对您有所帮助。这是工作结果。在循环外将变量设为false,这给了我我想要的答案。

    $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.";
    }