php mysqli check if any result exist [closed]

2019-08-16 03:19发布

问题:

I have a code to check user data already exist in mysql by mysqli like this :

    $SQL = "SELECT users.email,users.handle,userprofile.mobile FROM users,userprofile      
        WHERE users.email =? OR users.handle =? OR userprofile.mobile=?";
if ($stmt = $mysqli->prepare($SQL)) {
$stmt->bind_param("sss", $email,$username,$mobile);
$stmt->execute();
if($stmt->num_rows){
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_NUM);
    if($row[0] ==$email){echo 'email exist';}
    if($row[1] ==$username){echo 'username exist';}
    if($row[2] ==$mobile){echo 'mobile exist';}
}
else{
echo 'OK';
}

if works when the user data already exist. but if user data does not exist , the else does not work! why?

回答1:

The reason this is occurring is because your if statement is returning true, therefore it executes the code within it. $stmt->num_rows can return true, false or a int, so even if no rows have been affected, it is still returning a valid value

0 is a valid value, the if statement will only skip that part of the code if the logic returns false, so changing your code to the following will fix the issue.

if( $stmt->num_rows > 0) {
   // your code here
}


回答2:

This is because you are checking num_rows as it would returnfalse if no matches are found. It instead returns 0 in case no entry is matched, so I would rather suggest to check if num_rows is > 0

if($stmt->num_rows > 0){


标签: php mysqli