Search code examples
phpsqlmysqliprepared-statement

How to add number to username if it already exists


I am trying to make a school portal system for my coursework. Every student has a username which consists of the first letter of their name, and first 4 letters of their surname. To create this username automatically, I am using this in the page where the admins adds students.

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;

However, if for example two students with the same surname, and same initial letter of their name are entered, it would come up with an error, so I need it to add 01 the first time that username is used, 02 the second time and so on. Example. Name = Test, Surname = Student For this example I would like the first username with those letters to be TStud01, the second to be TStud02...


Solution

  • You need to fetch the count of usernames starting with the common pattern from the database and then increment this by 1. Then you can pad it with 0 and save that in the database.

    Few points to note:

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

    Results in:

    enter image description here