简体   繁体   中英

How to check if random created number already exist

I am creating a unique reference number using php.

I would like to check if the number already exist in the database.

Here is my current code:

<?php

function generateRandomString($length = 3) {
    $characters = 'ABCDEFGHJKLMNOPQRSTVWXYZ';//No "I"
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$var = generateRandomString();


$random = rand(1000, 9999);
$randoms = rand(1000, 9999);

$tokennr = "I$var-$random" . "0" . $randoms;


require_once('connect_pdo.php');
header('Content-Type: text/html; charset=utf-8');
$stmt = $conn->prepare("SELECT UniqueNumber FROM `MyTable` ");
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
   $uniqueref = $row["UniqueNumber"];
}
if($tokennr == $uniqueref){
     $tokennrs = "I$var-14$random" . "6" . $randoms;
     $token = $tokennrs;
}else{
    $token = $tokennr;
}
echo $token;

?>

It seems that the code still uses the unique number even if it already exist. (I hard-coded some test numbers).

I do not want to use a number if it already exist.

Rather than getting every row from the table and comparing it to the new 'unique reference' add a where clause to the query containing the new unique and you wont have to walk through possibly 1000's of rows to see if it is a duplicate.

Hopefully this column will be indexed in the database so this will be very quick as well.

<?php

function generateRandomString($length = 3) {
    $characters = 'ABCDEFGHJKLMNOPQRSTVWXYZ';//No "I"
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}


require_once('connect_pdo.php');
header('Content-Type: text/html; charset=utf-8');

// prepare staement outside the loop it only has to be done once
$stmt = $conn->prepare("SELECT COUNT(UniqueNumber) as cnt 
                        FROM `MyTable` 
                        WHERE UniqueNumber = :uniq");

// automate the dup fiddle byte
$fiddlebyte = 0;

$var = generateRandomString();
$random = rand(1000, 9999);
$randoms = rand(1000, 9999);
$token = "I$var-$random" . $fiddlebyte . $randoms;

// may get more than one dup so loop until no dup
while ( true ) {

    $stmt->execute([':uniq'=> $token]);

    $cnt = $stmt->fetchColumn();

    if ( $cnt == 0 ) { 
        continue;    // stop the while loop its unique
    } 
    $fiddlebyte++;
    $token = "I$var-$random" . $fiddlebyte . $randoms;
}
echo $token;

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM