php - 如何使用 php 使用户名条目必须是唯一的

标签 php mysql

<分区>

所以,我有一个注册表单,我希望所有用户名(电子邮件地址)都必须是唯一的,我这样做是为了使数据库条目必须是唯一的,但是用户得到的错误是我的通用错误一个(请参阅 $message),我可以将其更改为另一条消息,但是用户将不知道该帐户是否由于服务器端错误或电子邮件地址重复而未创建。

$message = 'Sorry there must have been an issue creating your account';

我一直在努力获得的是一种自定义错误的方法,当用户名已被使用时,它会显示类似以下内容的内容:“抱歉,此电子邮件已被使用”。

下面是我的注册表格的代码(我没有做这个):

<?php

session_start();

if( isset($_SESSION['user_id']) ){
    header("Location: restricted.php");
}

require 'database.php';

$message = '';

if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['surname'])):

    // Enter the new user in the database
    $sql = "INSERT INTO users (email, password, firstname, surname) VALUES (:email, :password, :firstname, :surname)";
    $stmt = $conn->prepare($sql);

    $stmt->bindParam(':email', $_POST['email']);
    $stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
    $stmt->bindParam(':firstname', $_POST['firstname']);
    $stmt->bindParam(':surname', $_POST['surname']);


    if( $stmt->execute() ):
    $message = 'Successfully created new user';
    else:
    $message = 'Sorry there must have been an issue creating your account';
    endif;

endif;

?>

<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <?php include '../header.php'; ?>
</head>
<body>

    <?php if(!empty($message)): ?>
        <p><?= $message ?></p>
    <?php endif; ?>

    <h1>Register</h1>
    <span>or <a href="login.php">login here</a></span>

    <form action="register.php" method="POST">

        <input type="text" placeholder="Enter your email" name="email">
        <input type="password" placeholder="and password" name="password">
        <input type="password" placeholder="confirm password" name="confirm_password">
        <input type="text" placeholder="Enter your first name" name="firstname">
        <input type="text" placeholder="Enter your surname" name="surname">
        <input type="submit">

    </form>

</body>
</html>

最佳答案

首先运行一个select 查询来检查用户名/电子邮件地址是否已经存在。

如果存在则返回错误,如果不存在则插入数据库。 您不仅应该验证您的 post 是否为空。此外,如果数据有效,如正确的电子邮件标记、相同的密码、唯一的用户名等

关于php - 如何使用 php 使用户名条目必须是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888420/

相关文章:

php - Joomla,如何在最新模块中显示类别名称

php - 如何显示mysql求和查询的值

php - MySQL 更新另一个表的连接信息

查询 MySQL 数据库时支持 PHP 和阿拉伯语

php - 选项国家html与mysql

mysql - 像 phpMyAdmin 这样的 MySQL 数据库离线工具?

php - 无法找出语法错误,意外的 T_ENCAPSED_AND_WHITESPACE,需要 T_STRING 或 T_VARIABLE 或 T_NUM_STRING

javascript - JSON 错误 : SyntaxError: JSON. 解析:JSON 数据第 2 行第 1 列出现意外字符

php - 在 Windows 上使用 iconv() 进行音译

php - 使用 PHP 的 PDO 将 "number of views"保存到 MySQL 中记录的表行?