Object of class mysqli_result could not be convert

2019-09-22 04:56发布

I am working on a simple login. One piece of logic is that if the username does not exist then they get an error message and they get redirected to a registration page. However when I run my code I keep getting the error described above and no matter what I enter as a username it still comes back as true.

   $res = $mysqli->query("SELECT Count(`userID`) FROM `users` WHERE `UserName` = '$username'");
    if($res ==0){
        return false;
    }
    else
        return true;
}

I control the database as I'm developing it and thus know what usernames are in it. I was under the impression that if I put in a username that was in the database the count would be 1 and thus would return true, likewise if I entered a name that is not in the database then the count would be 0 and thus $res would be false?

标签: php mysqli
2条回答
不美不萌又怎样
2楼-- · 2019-09-22 05:27

You still have to count! The return value of mysqli::query is NOT an integer, it is a result object.

if ($res->num_rows == 0) {
    return false;
} else {
    return true;
}

It is considered not the best coding style to verbosely create the return value.

return ($res->num_rows > 0); // will be true if result is bigger than 0

And this leads to the question: What if there are TWO OR MORE rows returned?

查看更多
聊天终结者
3楼-- · 2019-09-22 05:43

It could be done like that:

return ($res && $res->num_rows >= 1) ;
查看更多
登录 后发表回答