Trying to complete an add user script. Nothing out of the ordinary, however I have transitioned over to using prepared statements, and I am trying to get better at creating my own functions.
<?php
include("../include/sessions.php");
if(isset($_POST['criteria']))
{
$value = $_POST['criteria'];
$firstname = htmlspecialchars(trim($value['firstname']));
$lastname = htmlspecialchars(trim($value['lastname']));
// few more
// set blank variable to be passed into function
$dbusername = '';
// pass necessary variables into the function
// $dbc is the database connection needed for the prepared statement
function createUsername($firstname, $lastname, $dbusername, $dbc)
{
// check if $user ever matches $dbusername, if so, rerun loop
while($user == $dbusername)
{
$digits = 4;
$randomNumber = rand(pow(10, $digits-1), pow(10, $digits)-1);
// get first 3 letters of firstname
$first3 = substr($firstname, 0, 3);
// get first 3 letters of lastname
$last3 = substr($lastname, 0, 3);
// set user to $first3, $last3, and $randomNumber
$user = $first3 . '' . $last3 . '' . $randomNumber;
// prepare statement
$select = "SELECT username FROM users WHERE username = ?;";
$stmt = $dbc->prepare($select);
// pass in the new $user
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// if the created user happens to exist in the database, set it to $dbusername
$dbusername = $row['username'];
// rerun the loop if this happens
}
// if no matches, return the new username
return $user;
}
}
$user = createUsername($firstname, $lastname, $dbusername, $dbc);
echo 'username is ' . $user; // username should look like this: johbea3647
?>
I tried to notate the code as much as possible. But just in case, I'll break it down here...
The idea is to take create a brand new username that begins with the first 3 letters of the first and last name, then add a random 4 digit number to the end.
Hopefully, as long as the seemingly random username does not exist in the database, then return the new username. However, in the event the random username happens to exist, then run the loop again until there is no match.
I hope this all makes sense. Please review my code and see if there are any problems, or if there is a way to possibly simplify it all.
So far, everything seems to work. I'm just not too sure about that while
loop.
htmlspecialchars()
does? The call seems highly inappropriate here. \$\endgroup\$