php mysqli check if any result exist [closed]

三世轮回 提交于 2019-12-25 01:55:26

问题


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){


来源:https://stackoverflow.com/questions/16639598/php-mysqli-check-if-any-result-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!