count($existuser)
函數總是返回1.即使沒有具有該名稱或電子郵件的用戶。PDO用戶驗證
下面是代碼:
function registerUser($username, $password, $passwordagain, $email, $mcname) {
include $_SERVER['DOCUMENT_ROOT'] . "/config/config.php";
$conn = new PDO('mysql:host=' . $ip . ';dbname=' . $database, $username, $password);
$validusername = "/^[a-z0-9]+$/";
$validpassword = "/^[A-Za-z0-9]+$/";
$validemail = "/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/";
$validmcname = "/^[A-Za-z0-9]+$/";
$error = 0;
if (strlen($username) < 4 || strlen($username) > 24) {
$error = 1;
}
if (strlen($password) < 6 || strlen($password) > 24) {
$error = 1;
}
if (strlen($mcname) < 4 || strlen($mcname) > 24) {
$error = 1;
}
if (!preg_match($validusername, $username)) {
$error = 1;
}
if (!preg_match($validpassword, $password)) {
$error = 1;
}
if (!preg_match($validemail, $email)) {
$error = 1;
}
if (!preg_match($validmcname, $mcname)) {
$error = 1;
}
if ($password != $passwordagain) {
$error = 1;
}
//test
$userquery = $conn->query('SELECT * FROM users WHERE username="' . $username . '"');
$existuser = $userquery->fetch();
echo count($existuser);
//test
if (count($existuser)) {
$error = 1;
echo "<div class='erroralert'>Username already exists!</div>";
}
//test
$emailquery = $conn->query('SELECT * FROM users WHERE email="' . $email . '"');
$existemail = $emailquery->fetch();
//test
if (count($existemail)) {
$error = 1;
echo "<div class='erroralert'>E-mail already exists!</div>";
}
if ($error != 1) {
$encryptedpassword = hash('sha512', $password);
$registeruser = $conn->query("INSERT INTO users(username, password, email, mcname) VALUES ('$username', '$encryptedpassword', '$email', '$mcname')");
echo "<div class='successalert'>Succesfully registred</div>";
}
}
我不明白您的查詢發佈,也將是對你的調試過程中改變你的錯誤狀態,所以你可以找出什麼是錯的你/用戶正在輸入該功能。 –
請參閱:http://php.net/faq.passwords.php - 您也可以將驗證的長度限制放入正則表達式中(您已經使用電子郵件正則表達式執行此操作),並且您應該在此處使用準備好的語句,因爲您不要處理驗證結果。 – hakre