无法将mysqli_result类的对象转换为int,并且所有条目均返回true [英] Object of class mysqli_result could not be converted to int and all entries return true
问题描述
我正在进行一个简单的登录.一种逻辑是,如果用户名不存在,则他们会收到一条错误消息,并将其重定向到注册页面. 但是,当我运行代码时,仍然收到上述错误,无论我以用户名输入什么,它仍然会返回true.
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;
}
我在开发数据库时控制数据库,因此知道其中包含什么用户名.我的印象是,如果我输入数据库中的用户名,则计数将为1,因此将返回true,同样,如果我输入的名称不在数据库中,则计数将为0,因此为$ res会是假的吗?
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?
推荐答案
您仍然要数数! mysqli :: query的返回值不是整数,它是结果对象.
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?
这篇关于无法将mysqli_result类的对象转换为int,并且所有条目均返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!