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["UniqueRefNr"];
}
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.
Aucun commentaire:
Enregistrer un commentaire