HTML PHP - 如何检查用户名是否已存在

时间:2016-08-15 09:06:50

标签: php html mysql

该脚本已经正常工作但我想插入一个仅在用户名尚未使用时才允许的命令。

if (isset($_POST['submit'])) {
    $firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
    $lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
    $position = htmlentities($_POST['position'], ENT_QUOTES);
    $username = htmlentities($_POST['username'], ENT_QUOTES);
    $password = htmlentities($_POST['password_two'], ENT_QUOTES);
    $uniqid = uniqid('', true);
    if ( $firstname == '' || $lastname == '' ||  $position == '' || $username == '' || $password == '') {
        $error = 'ERROR: Please fill in all required fields!';
        renderForm($error, $firstname, $lastname, $position, $username, $password);

    } else {
        if ($stmt = $connection->prepare("INSERT INTO employee (uniqid, firstname, lastname, position, username, password) VALUES (?, ?, ?, ?, ?, ?)")) {
            $stmt->bind_param("ssssss", $uniqid, $firstname, $lastname, $position, $username, $password);
            $stmt->execute();
            $stmt->close();
        } else {
            echo "ERROR: Could not prepare SQL statement.";
        }
        header("Location: regemployee.php");
    }
} else {
    renderForm();
}

2 个答案:

答案 0 :(得分:1)

在数据库中使用户名唯一,然后当您尝试再次将相同的用户名插入数据库时​​,插入将出错。

或者,您可以执行SELECT * FROM employee WHERE username = ?并检查结果是否为> 0

然后你就会知道它已经存在了。

答案 1 :(得分:0)

执行另一个SELECT查询,检查提交的username是否已存在:

$stmt = $connection->prepare("SELECT * FROM employee WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();

然后得到结果数:

$stmt->store_result();
$noofres = $stmt->num_rows;
$stmt->close();

然后,创建一个条件,如果它不存在,它将执行插入查询:

if($noofres == 0){

    /* INSERT QUERY HERE */

} else {

    echo 'Username already taken.';

}