注册表格未显示验证错误

时间:2013-07-03 15:18:32

标签: php

当用户输入已经使用的用户名时,我遇到了出现错误的问题。

在下面的代码中,数据库在成功输入后会更新。但是,如果使用重复的用户名创建条目,则该条目将放在数据库中,并且不会显示任何错误消息。我已经看过网并尝试了一些方法,这就是我到目前为止所做的。谢谢你看看:))

<?php
// Create connection
$con = mysqli_connect('172.16.254.111', "user", "password", "database"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
} //sql syntax below, first line is collumn titles on the db and second line is values from the html document
//$_post is a form of sending information in php
{
    $username   = strip_tags($_POST['username']);
    $password   = md5(strip_tags($_POST['pass']));
    $password2  = md5(strip_tags($_POST['pass2']));
    $fullname   = strip_tags($_POST['fullname']);
    $email      = strip_tags($_POST['email']);
    $department = strip_tags($_POST['department']);
    if ($password != $password2) //password doestn equal same as password 2 then the message below is displayed (working)
        {
        echo "<H2>password doesn't match</H2>";
    }
    $usercheck  = "SELECT * FROM Users WHERE username=$username";
    $usercheck2 = mysql_query($usercheck);
    if (mysql_fetch_assoc($usercheck2)) {
        echo "<H2>This username already exists, please pick another</H2>";
    } else {
        $sql = "INSERT INTO Users(username, password, password2, email, fullname, department) 
                                                                                VALUES('$username','$password','$password2','$email','$fullname','$department')";
        if (!mysqli_query($con, $sql)) {
            die('Error: ' . mysqli_error($con));
        }
        echo "<H2>Registration was successful, please use the access console above</H2>";
    }
}
?>

请原谅代码中的任何评论;我是PHP和编码的初学者。

2 个答案:

答案 0 :(得分:1)

你错过了一些引用。试试这个:

$usercheck = "SELECT * FROM Users WHERE username = '$username'";
// ----------------------------------was missing---^---------^
$usercheck2 = mysql_query($usercheck);
if (mysql_num_rows($usercheck2)) {
    echo 'user exists';
}

此外,您不应该使用mysql_*功能。请查看使用PDO

答案 1 :(得分:0)

更改$ usercheck =“SELECT * FROM Users WHERE username = $ username”; 为此$ usercheck =“SELECT * FROM Users WHERE username ='$ username'”;告诉我它是否有效。

相关问题