What are the best practices for checking the existence of a string in a database and appending numbers in PHP?

When checking the existence of a string in a database and appending numbers in PHP, it is important to first query the database to see if the string already exists. If it does, then you can append numbers to make the string unique. One common approach is to use a loop to keep incrementing a counter until a unique string is found.

// Assuming $conn is the database connection and $inputString is the string to check
$inputString = "example";
$counter = 1;
$uniqueString = $inputString;

// Check if the string already exists in the database
$query = "SELECT * FROM table_name WHERE column_name = '$uniqueString'";
$result = mysqli_query($conn, $query);

// If the string already exists, keep appending numbers until a unique string is found
while(mysqli_num_rows($result) > 0){
    $uniqueString = $inputString . $counter;
    $query = "SELECT * FROM table_name WHERE column_name = '$uniqueString'";
    $result = mysqli_query($conn, $query);
    $counter++;
}

// At this point, $uniqueString contains the unique string to be used
echo $uniqueString;