0

好的,有这个代码,它是一个注册表单,但我无法检查是否已经使用了用户名?它所做的只是再次在数据库中创建相同的用户名,而不是返回“用户名已被使用”,如果有人可以提供帮助,将不胜感激。

$checkusernametaken = mysql_query("SELECT FROM users (username) WHERE username=username");
 if(mysql_num_rows($checkusernametaken)>=1)
    {
        echo"Username already exists";
    }
 else
    {
        $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
        $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
        $stmt->execute();
        return "Registration Successful Welcome " + $checkusernametaken + "<br/> <a href='index.php'>Login Now</a>";
    }

这是我使用的代码,在评论中每个人的帮助下,我得到了它,谢谢大家!

try {
        $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
        $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
        $stmt->execute();
        return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
    }
    catch( PDOException $e ) 
    {
         return "Username Taken <br/> <a href='register.php'>Try Again?</a>";
    }
4

2 回答 2

2

以下是该表的外观示例:

CREATE TABLE `users` (
`id` INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
`username` VARCHAR(30) NOT NULL UNIQUE,
`password` VARCHAR(64) NOT NULL
);

现场演示。

最简单的方法是,如果您更改表格以使字段用户名唯一,这样如果您尝试插入相同的用户名,则会导致重复输入错误,您可以像这样轻松捕获:

try
{
    $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
    $stmt = $con->prepare($sql);
    $stmt->bindValue("username", $this->username, PDO::PARAM_STR);
    $stmt->bindValue("password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR);
    $stmt->execute();
    return "Registration Successful Welcome {$checkusernametaken}<br/><a href=\"index.php\">Login Now</a>";
}
catch (PDOException $e)
{
    if ($e->getCode() == 1062)
    {
        return "The selected username is not available...";
    }
    else
    {
        // More info at: http://php.net/manual/en/class.pdoexception.php
        return "Handle any other errors here.";
    }
}
于 2013-10-12T02:23:20.880 回答
0
$checkusernametaken = mysql_query("SELECT FROM users (username) WHERE username=username");

在这里你应该改为

$checkusernametaken = mysql_query("SELECT * FROM `users` WHERE lcase(`username`) = lcase('".mysql_escape_string($this->username)."')") or die(mysql_error());
于 2013-10-12T02:27:20.080 回答