php mysqli检查是否存在任何结果

AF.*_*F.P 0 php mysqli

我有一个代码来检查mysqli中已经存在的用户数据,如下所示:

    $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';
}
Run Code Online (Sandbox Code Playgroud)

如果在用户数据已存在时有效.但如果用户数据不存在,则else不起作用!为什么?

Jak*_*all 5

发生这种情况的原因是因为你的if语句返回true,因此它执行其中的代码.$stmt->num_rows可以返回true,false或者int,即使没有行受影响,它仍然返回一个有效值

0是一个有效值,if语句只会在逻辑返回false时跳过代码的那一部分,因此将代码更改为以下内容将解决问题.

if( $stmt->num_rows > 0) {
   // your code here
}
Run Code Online (Sandbox Code Playgroud)