使用名字和姓氏创建唯一的8字符用户ID,比较MySQL表中的现有用户ID,在唯一时插入

I would like to create a unique 8 character userid using the values contained in $first_name and $last_name. 1st digit will be a number between 1 and 9. Second digit will be the user's first initial of their first name. last 6 digits will be the first six digits of their last name. All lower case.

ex:

$first_name = "Jack";
$last_name = "Exampleman";

$counter = 1;
$userid = $counter.strtolower(substr($first_name, 0, 1)).strtolower(substr($last_name, 0, 6));

produces: 1jexampl

This works great for creating a SINGLE $userid. However, I need to check against a MySQL table to see if it is unique. If it does not exist, insert. If it does exist add 1 to counter, then check to see if the new modified $userid exists. Repeat the check and adding to the counter (to a maximum $counter value of 8).

WHAT IS THE LOGIC to iterate the MySQL check, until the proposed $userid is confirmed unique? I have something like:

    $connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT userid FROM staff2 WHERE userid = '$userid'";
$result = $connect->query($sql);
    while($row = $result->fetch_assoc()) {
        $counter ++;
        $userid = $counter.strtolower(substr($first_name, 0, 1)).strtolower(substr($last_name, 0, 6));
}
$connect->query("INSERT INTO staff2 (userid, first_name, last_name) VALUES('$userid', '$first_name', '$last_name')");

I was able to use recursion to solve as follows:

    //initial running of the function:
userExists($userid, $connect,  $counter, $first_name, $last_name);

function userExists($userid, $connect,  $counter, $first_name, $last_name) {

    // someone with the same userid exists in the database.
$sql = "SELECT userid FROM staff2 WHERE userid = '$userid'";
$result = $connect->query($sql);

    while($row = $result->fetch_assoc()) {
        print "It appears that $userid exists!<P>";

        $counter ++;
        //print "The new counter value should be one more than above, it's now: $counter. <br> The userid at this point is still: $userid <P>";
        $userid = $counter.strtolower(substr($first_name, 0, 1)).strtolower(substr($last_name, 0, 6));
        userExists($userid, $connect2,  $counter, $first_name, $last_name);
        return;

    }

    $connect->query("INSERT INTO staff2 (userid, first_name, last_name) VALUES('$userid', '$first_name', '$last_name')");
}

Hopefully this is helpful to others looking to create unique userid's using names :-)