0

下面是我编写的用于创建随机字符串的代码。效果很好。它还检查以确保生成的字符串不存在,如果存在,则生成另一个。但是,我还没有找到一种方法来检查生成的代码是否已经存在,以查看该代码是否存在。我最好做一个 elseif 语句吗?

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


?>

任何帮助表示赞赏:)

4

1 回答 1

1

尝试这个。

// 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;

干杯,

威廉

于 2013-09-03T21:35:04.317 回答