我已经创建了一个表单并使用php来检查数据库中是否存在用户名,如果是,那么表单将不会提交并回显用户名已被删除的表单,如果我填写表单并提交它有一个我知道的名字在数据库中,我得到的错误说用户名已经存在,但我也得到了说明的文字..感谢您注册
基本上它正确显示错误,但它仍然将所有数据提交到数据库
你能在我的代码中看到导致这种情况的任何内容吗?
//Check to see if the username is already taken
$query = "SELECT * FROM clients";
$result = mysql_query($query) or die(mysql_error()); // Get an array with the clients
while($row = mysql_fetch_array($result)){ // For each instance, check the username
if($row["username"] == $username){
$usernametaken = true;
}else{$usernametaken = false;}
}
// If the username is invalid, tell the user.
// Or else if the password is invalid, tell the user.
// Or else if the email or PayPal address is invalid, tell the user.
// Else, if everything is ok, insert the data into the database and tell
// the user they’ve successfully signed up.
if($usernametaken)
{
echo "That username has been taken.";
}
if(!preg_match('/^[a-zA-Z0-9]+$/', $username ))// If our username is invalid
{
echo "The username can only contain letters or numbers"; // Tell the user
}
else if(!preg_match('/^[a-zA_Z0-9]+$/', $password ))// If our password is invalid
{
echo "The password can only contain letters or numbers"; // Tell the user
}
// If our email or PayPal addresses are invalid
else if(!preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/", $email))
{
return "The email or PayPal address you entered is invalid."; // Tell the user
}
else{
// Inserts the data into the database
$result = mysql_query("INSERT INTO clients (client_ID, username, password, email, paypal)"."VALUES ('', '$username', '$pw', '$email', '$paypal')");
echo "Thank you for signing up.";
}
?>
答案 0 :(得分:1)
如果用户名不好,你需要突破你的功能。如果你不希望你的最后一行运行,你可以在preg匹配之前添加else。基本上你的程序流程是
//if username taken
//if bunch of cases
//else add client
你的两个if语句没有任何区别。
你的SQL语句也是一个熊。您循环遍历数据库中的每个客户端以查看它是否重复。只需添加where语句
即可$query = "SELECT * FROM clients WHERE clientName = '$clientName'";
答案 1 :(得分:0)
如果发现用户名已被删除,则没有任何内容可以告诉脚本停止执行。像这样重构你的if-else语句:
if($usernametaken)
{
echo "That username has been taken.";
} else {
// If username is not taken...
}
答案 2 :(得分:0)
除了使用其他几个ifs,我建议您使用例外情况。
演示:
<?php
try
{
if ($usernametaken) throw new Exception('That username has been taken.');
// If we've reached here we know data has been checked properly
$result = mysql_query("INSERT INTO clients (client_ID, username, password, email, paypal)"."VALUES ('', '$username', '$pw', '$email', '$paypal')");
echo "Thank you for signing up.";
}
catch (Exception $e)
{
echo $e->getMessage();
}
?>