我的注册表单中包含以下代码,以防止创建多个用户名:
connect_db();
$check = mysql_query("SELECT username FROM school_users WHERE username = '$username'") or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 != 0) {
respond("error", "Sorry, the username ".$_POST['username']." is already in use. Please choose a different username.");}
但是,我也想在同一声明中检查电子邮件:
connect_db();
$check = mysql_query("SELECT username, email FROM school_users WHERE username = '$username' or email = '$email'") or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 != 0) {
if (???username???){
respond("error", "Sorry, the username ".$_POST['username']." is already in use. Please choose a different username.");}}
else if (???email???) {
respond("error", "Sorry, the username ".$_POST['username']." is already in use. Please choose a different username.");}}
答案 0 :(得分:2)
您可以尝试:
connect_db();
$check = mysql_query("SELECT 'User' validation
FROM school_users
WHERE username = '$username'
UNION ALL
SELECT 'Email'
FROM school_users
WHERE email = '$email'") or die(mysql_error());
$row = mysql_fetch_assoc($check);
if($row)
{
if ($row["validation"] == 'User') {
respond("error", "Sorry, the username ".$_POST['username']." is already in use. Please choose a different username.");}}
else if ($row["validation"] == 'Email') {
respond("error", "Sorry, the email ".$_POST['email']." is already in use. Please choose a different email.");}}
}
或者你可以单独做...
//Validate UserName
connect_db();
$check = mysql_query("SELECT username FROM school_users WHERE username = '$username'") or die(mysql_error());
$check2 = mysql_num_rows($check);
if ($check2 != 0) {
respond("error", "Sorry, the username ".$_POST['username']." is already in use. Please choose a different username.");}
//Validate Email
connect_db();
$checkEmail = mysql_query("SELECT email FROM school_users WHERE email = '$email'") or die(mysql_error());
$checkEmail2 = mysql_num_rows($check);
if ($checkEmail2 != 0) {
respond("error", "Sorry, the email ".$_POST['email']." is already in use. Please choose a different email.");}
此外,您的代码容易受到SQL注入攻击,并且您正在使用已弃用的MySQL php函数。如果您确实希望更好地使代码更容易受到攻击,请查看以下链接:
Why shouldn't I use mysql_* functions in PHP?
答案 1 :(得分:1)
您也可以在一个声明中执行此操作:
SELECT username
FROM school_users
WHERE username = '$username' or email = '$email'
如果您这样做,则需要将消息更改为用户。 。 。 “您的用户名或电子邮件(或两者)已在使用中。”
要在一个语句中自定义消息,您可以使用聚合:
select (case when max(username = '$username') = 1 and max(email = '$email' = 1
then 'both'
when max(username = '$username') = 1
then 'username'
when max(email = $email) = 1
then 'email'
end) as WherePresent
from school_users
WHERE username = '$username' or email = '$email'
如果一切正常,则返回0行。否则,它返回一行“两者”,“用户名”,“电子邮件”,表示哪个是重复的。