MySQLi创建随机字符串,但检查它不存在

Below is my code that i have written to create a random string. Works well. It also checks to make sure that the generated string doesn't already exist, and if it does, then it makes another one. HOWEVER i haven't yet worked out a way to make the code generated if one already exists be checked to see if that one exists. Would i be best doing an elseif statement?

PHP

<?PHP
require_once('dbConfig.php');
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

for ($i = 0; $i < 12; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
}
//$generatedId = "SPI-E7HN2SBIIF5W";
$generatedId = 'SPI-'.$randomString;

//Prepare select query
$statement = $db->prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");

//Determine variable and then bind that variable to a parameter for the select query ?
$id = $generatedId;
$statement->bind_param('s', $id);

//Execute and store result so that num_rows returns a value and not a 0
$statement->execute();
$statement->store_result();

//Bind result to a variable for easy management afterwards
$statement->bind_result($clientId);

// Generate a random ID for the user if the previously generated one already exists
if($statement->num_rows > 0){
    $randomstring = '';
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

    for ($i = 0; $i < 0; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    $generatedId = 'SPI-'.$randomString;
    echo $generatedId;
} else {
    // If there's no issue with what's been created, echo it out :)
    echo $generatedId;
}


?>

Any help is appreciated :)

try this.

// initialize a variable to hold the last generated id, 
$generatedId = '';
// and another to hold the returned client_unique_id, 
$clientId = '';

setup your prepared statement
bind the parameter, 
$statement->bind_param('s', $id)
do
{
   generate a new Id. (Code for generating random id goes here).
   $generatedId = '...';
   // bind the generated id to the prepared statement. 
   $id = $generatedId
   // execute the prepared statement, 
   $statement->execute()
   // fetch the results into $clientId
   $statement->bind_result($res);
   while($statement->fetch()) {
       $clientId = $res;
   }
} while ($clientId != '');

$statement->close();
// echo the last generated Id
echo $generatedId;

cheers,

William