tecksup tecksup - 6 months ago 20
PHP Question

php mysqli:query if returns true?

I am trying to check my database row, my code works but im having problems with my if and else statements. The code below is what is not working. On the PHP mysqli::query page it says that it returns false on error. if thats the case my else statement should run, but instead the code just skips the else statement completely.

$conn = new mysqli($servername, $username, $password, $database);
if ($result = mysqli_query($conn,"SELECT * FROM codes WHERE email='" .$email. "'")) {
while ($row = mysqli_fetch_array($result)) {
$input_box = $row['code'];
}
}
else {
$emailErr = '<span style="color:red;font-size:16px">Email did not match any lists.</span>';
$email_input = test_input($_POST["email"]);
}
$conn->close();


What is wrong with my code, or am i misunderstanding how it returns false and when its false. I would love it if you could help me get the else statement running!

EDIT: to clarify the code does the if statement when it should correctly, but when it shouldn't the else statement doesn't run.

Answer

As @Dagon said, ...query will return true if no matches are found

So instead of relying solely on mysqli_query(), use mysqli_num_rows() to check if the SELECT query returned any row or not, like this:

$conn = new mysqli($servername, $username, $password, $database);
if ($result = mysqli_query($conn,"SELECT * FROM codes WHERE email='" .$email. "'")) {
    if(mysqli_num_rows($result)){
        while ($row = mysqli_fetch_array($result)) {
            $input_box = $row['code'];
        }
    }else{
        $emailErr = '<span style="color:red;font-size:16px">Email did not match any lists.</span>';
        $email_input = test_input($_POST["email"]);
    }

}
$conn->close();

Here's the reference: