php - 检查用户登录时的多种条件

标签 php mysql

我想完成以下任务:

如果用户名或密码字段为空,则通知用户。如果用户名已存在,则不插入数据库并通知用户创建不同的名称。如果用户名唯一且密码不为空,则将用户名返回给用户。 截至目前,它总是返回“请输入不同的用户名”。我相信这个问题与数据库查询有关,但我不确定。如果有人可以看看我是否犯了错误,我非常感激,谢谢。

if ($userName or $userPassword = null)
{

  echo "Please enter a user name and password or return to the homepage.";

}

elseif (mysql_num_rows(mysql_query("SELECT count(userName) FROM logininfo WHERE userName = '$userName'")) ==1)

{

  echo "Please enter a different user name.";

}

elseif ($userName and $userPassword != null)

{

  echo "Your login name is: $userName";

}

最佳答案

if ($userName or $userPassword = null)

这会检查 $userName 是否为 true(相当于 $userName == true),并且您分配 null$userPassword。你想要像 $userName == '' || 这样的东西$userPassword == ''.

"SELECT count(userName) FROM logininfo WHERE userName = '$userName'"

SQL injection的风险。使用mysql_real_escape_string在将值插入查询之前!

此外,mysql_num_rows始终返回 1 行,因此该表达式始终为true。您需要查看这一行的

elseif ($userName and $userPassword != null)

如果此检查符合您的预期,则它与第一个检查相比是多余的。

使用这样的东西:

function validateUser($username, $password) {
    if ($username == '' || $password == '') {
        return 'Please enter a user name and password or return to the homepage.';
    }

    $query = sprintf("SELECT COUNT(*) as `count` FROM `logininfo` WHERE `userName` = '%s'",
                     mysql_real_escape_string($username));
    $result = mysql_query($query);
    if (!$result) {
        trigger_error(mysql_error());
        return false;
    }
    $result = mysql_fetch_assoc($result);
    if ($result['count'] > 0) {
        return 'Please enter a different user name.';
    }

    return "Username: $username";
}

$result = validateUser($username, $password);
if (!$result) {
    // something went wrong, deal with it
} else {
    echo htmlentities($result);
}

请注意,这距离理想的代码还很远,但我希望您能明白。

关于php - 检查用户登录时的多种条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4590203/

相关文章:

php - 无法向sql表中插入数据

PHP 登录页面错误

mysql - RDS 实例 CPU 利用率

python - 如何根据用户登录执行不同的数据库查询

PHP 允许的内存大小 内存大小耗尽

php - 如果给出错误的 php GET 凭据,如何返回登录页面?

php - 无法通过 CodeIgniter 连接到远程数据库

php - 如何在CodeIgniter上上传图像并将其显示在另一个页面上

php - 如果存在两行且值等于,则从数据库获取值

mysql - 在巨大的 MySQL 表上进行 INSERT ... SELECT