我正在使用PHP构建登录表单,表单验证的一部分是检查用户是否“活动”,这是mysql表用户中的整数,等于0或1 (1是被激活的)。在我当前的设置中,如果用户没有活动帐户,则无法登录。我实现这一目标的第一次尝试是:
//This code won't work because the query is an object, not an integer.
elseif(mysqli_query($connection, "SELECT COUNT('ID') FROM users WHERE username='$usernamelogin' AND 'active'='1'") < 1) {
echo('Account not activated. ');
}
但那不起作用,因为结果是一个对象,而不是一个int。所以,我搜索了如何解决这个问题,并给出了以下解决方案。
//if 1, account is active, if 0, account is inactive
$result = mysqli_query($connection, "SELECT COUNT('ID') FROM users WHERE username='$usernamelogin' AND 'active'='1'");
$row = mysqli_fetch_assoc($result);
$booly = ($row != 1) ? 1 : 0;
echo $booly;
然而,这段代码只给出了1的答案,即使我希望它给出0.我哪里出错了?我可以使用哪些其他方法来实现此功能?
更新
我确实错误地使用单引号而不是反引号,所以我尝试实现以下所有变体(我相信第一个是正确的,但是当它不起作用时尝试了所有其他变体)。他们都没有改变我的结果。
"SELECT COUNT(`ID`) AS count FROM users WHERE username='$usernamelogin' AND 'active'='1'"
"SELECT COUNT(`ID`) FROM users WHERE username='$usernamelogin' AND active='1'")
"SELECT COUNT(`ID`) AS count FROM users WHERE 'username'='$usernamelogin' AND 'active'='1'"
"SELECT COUNT(`ID`) FROM users WHERE 'username'='$usernamelogin' AND 'active'='1'")
"SELECT COUNT(`ID`) AS `count` FROM `users` WHERE `username`='$usernamelogin' AND `active`='1'"
"SELECT COUNT(`ID`) FROM `users` WHERE `username`='$usernamelogin' AND `active`='1'")
我也尝试过这些,但无济于事:
mysqli_query($connection, "SELECT COUNT(`ID`) FROM users WHERE username=$usernamelogin AND `active`='1'");
mysqli_query($connection, "SELECT COUNT(`ID`) FROM users WHERE username=$usernamelogin AND active='1'");
SOLUTION:
在代码中实现的解决方案:
$result = mysqli_query($connection, "SELECT COUNT(`ID`) AS count FROM users WHERE username='$usernamelogin' AND `active`='1'");
$row = mysqli_fetch_assoc($result);
if($row['count'] == true) {
echo('account not active'); }
答案 0 :(得分:0)
试试这个:
$result = mysqli_query($connection, "SELECT COUNT(`ID`) AS count FROM users WHERE username='$usernamelogin' AND `active`='1'");
$row = mysqli_fetch_assoc($result);
var_dump($row['count'] < 1);
编辑: 将单引号更改为引号。
答案 1 :(得分:0)
你在ID字段周围有单引号 - 所以它是一个字符串。 尝试删除它们或使用字段标识符周围的标记:
SELECT COUNT(`ID`) FROM users
您还可以在插入SQL的变量周围使用单引号,因此最终修复将是:
"SELECT COUNT(`ID`) FROM users WHERE username=$usernamelogin AND `active`='1'"