【问题标题】:HTML PHP - How to check if the username already existedHTML PHP - 如何检查用户名是否已经存在
【发布时间】:2016-08-15 17:10:34
【问题描述】:

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

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();
}

【问题讨论】:

  • 在将其插入数据库之前,请检查是否使用发布的用户名进行选择,如果查询返回值 0,您可以插入,否则会出现错误消息而不插入。
  • select count(*) from YOUR_TABLE where YOUR_CONDITION
  • 在 else 部分中,您在从表中选择数据后将其设置为 if else。 if($count==0){// Insert Coding goes here } else {//Error message goes here}.
  • 你能在我现有的代码中插入你的代码吗?谢谢

标签: php html mysql


【解决方案1】:

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

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

那么你就会知道它已经存在了。

【讨论】:

  • 用户名是唯一的。你能在我的代码中插入你的答案吗?谢谢
【解决方案2】:

执行另一个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.';

}

【讨论】:

  • 我将在哪里插入新的 sql 查询?
  • 关于在哪里插入 sn-ps 的代码怎么样,我是网络新手。谢谢
  • 你好先生在吗?
  • @Maki - 您只需将插入查询放入 if() 条件中
猜你喜欢
  • 2015-06-17
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 2015-03-04
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多