我創建了一個表單並使用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.";
}
?>
所以,我會只使用 - $查詢= 「SELECT * FROM客戶其中username = '$用戶名'」; – Gezzamondo
正確。那麼只要你的查詢結果至少有一行,你就知道它已經被使用了。我還會在你的數據庫用戶名列中添加一個唯一的約束。這將防止您的代碼中的錯誤允許用戶創建重複的用戶名。那會造成各種各樣的問題。錯誤發生! – mrtsherman
所以在該行後,仍然使用此代碼 - $結果= mysql_query($查詢)或死(mysql_error()); ($ row = mysql_fetch_array($ result)){//對於每個實例,檢查用戶名 \t if($ row [「username」] == $ username){ \t \t \t $ usernametaken = true; \t} else {$ usernametaken = false;} } – Gezzamondo