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