0

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

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

<?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 和一般编码的初学者。

4

2 回答 2

1

你错过了一些报价。尝试这个:

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

此外,您不应该使用这些mysql_*功能。研究使用PDO

于 2013-07-03T15:23:10.637 回答
0

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

于 2013-07-03T15:23:56.047 回答