0

我正在使用 PHP 构建登录表单,表单验证的一部分是检查用户是否“活跃”,这是 mysql 表 users 中的一个整数,等于 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'");

解决方案:

实现到代码中的解决方案:

$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'); }
4

2 回答 2

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

编辑:将单引号更改为反引号。

于 2013-08-04T15:40:39.333 回答
0

您在 ID 字段周围有单引号 - 所以它是一个字符串。尝试删除它们或在字段标识符周围使用 ` 标记,如下所示:

SELECT COUNT(`ID`) FROM users

您还可以在插入 SQL 的变量周围加上单引号,因此最终修复将是:

"SELECT COUNT(`ID`) FROM users WHERE username=$usernamelogin AND `active`='1'"
于 2013-08-04T15:47:42.187 回答