如果已经存在,如何将数字添加到用户名

How to add number to username if it already exists

我正在尝试为我的课程制作一个学校门户系统。每个学生都有一个用户名,由他们名字的第一个字母和姓氏的前 4 个字母组成。为了自动创建这个用户名,我在管理员添加学生的页面中使用了这个。

if (isset($_POST["btnAddUser"])) {
    //preparing statement to protect against sql injections
    $stmt = $conn->prepare("INSERT INTO tbluser (Username, Password, Role) VALUES (?,?,?)");
    $stmt->bind_param("sss", $usernamenew3, $password, $a);
    $password = $_POST["s_password"];
    $password = md5($password);
    $name = $_POST["s_name"];
    $surname = $_POST["s_surname"];
    $dob = $_POST["s_dob"];
    $a = "Admin";
    $usernamenew = substr($name, 0, 1);
    $usernamenew1 = substr($surname, 0, 4);
    $usernamenew3 = $usernamenew.$usernamenew1;

但是,比如两个同姓的同学,输入相同的姓名首字母,就会报错,所以我需要在第一次使用用户名时加01, 02 第二次等。 例子。姓名 = 测试,姓氏 = 学生 对于这个例子,我希望第一个带有这些字母的用户名是 TStud01,第二个是 TStud02...

您需要从数据库中获取以通用模式开头的用户名的计数,然后将其递增 1。然后您可以用 0 填充它并将其保存在数据库中。

注意几点:

  • 切勿以明文形式或使用 MD5/SHA1! 存储密码,仅存储使用 PHP 的 password_hash(), which you can then verify using password_verify(). Take a look at this post: and learn more about bcrypt & password hashing in PHP 创建的密码哈希。确保列为 VARCHAR(255).
  • 改用mb_substr(),因为名称可以包含非拉丁字母。
  • 要在 mysqli 中使用 LIKE,您必须在 PHP 中连接 %,然后将该变量绑定到查询。
  • 要了解如何使用 MySQLi 获取匹配行的计数,请参阅 How to get count of rows in MySQL table using PHP?
if (isset($_POST["btnAddUser"])) {
    $password = password_hash($_POST["s_password"], PASSWORD_DEFAULT);
    $name = $_POST["s_name"];
    $surname = $_POST["s_surname"];
    $dob = $_POST["s_dob"];
    $a = "Admin";
    $fistLetter = mb_substr($name, 0, 1);
    $shortSurname = mb_substr($surname, 0, 4);
    $usernamenew = $fistLetter.$shortSurname;

    $searchString = $usernamenew.'%';

    $stmt = $conn->prepare('SELECT COUNT(Username) FROM tbluser WHERE Username LIKE ?');
    $stmt->bind_param('s', $searchString);
    $stmt->execute();
    $countUsername = $stmt->get_result()->fetch_row()[0];

    $usernamenew .= str_pad($countUsername+1, 2, '0', STR_PAD_LEFT);

    //preparing statement to protect against sql injections
    $stmt = $conn->prepare("INSERT INTO tbluser (Username, Password, Role) VALUES (?,?,?)");
    $stmt->bind_param("sss", $usernamenew, $password, $a);
    $stmt->execute();
}

结果: