Nathan Nathan - 6 months ago 8
PHP Question

Generate Random But Unique alphanumerical ID for fault codes

im looking to generate a random but unique ID for fault codes in my web application however so far i cant come up with the right solution and not sure where i would start

im looking for a solution that would use letters and numbers for example

Fault Code : AF-5754

as these relate do an error stored in the database i need them to be unique the id in the database is just a number

what possible methods are there for this

function randomstring($len)
{
$string = "";
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<$len;$i++)
$string.=substr($chars,rand(0,strlen($chars)),1);
return $string;
}


this returns a random string however its not very user friendly to read out over the phone

Answer

Why not generate a human friendly code from the unique auto-generated by sql id?

<?php
function getFrom($id) // Get a human-friendly code for unique id from database
{

$prefixes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // Prefix posibilities

$primaryPrefx  = "A"; // Another prefix to increase id limit

if($id > 259999)
{
$primaryPrefx = $prefixes[intval($id / 2600000)];
$id = $id % 2600000;
}

$prefix = "";  // Prefix to be used
$errorCode = "";  // The integer to be added after the prefix

$prefix = $prefixes[intval($id / 100000)]; // get the prefix based on $id ( < 10000 => A , 10000 => B, 20000 => C, 30000 => D etc...) 


$id = $id % 100000; // now for the integer part (% returns remainder of division. This gets rid of > 9999 part)

if($id < 10000)
{
  $errorCode .= "0"; // We need five digits after prefix
if($id < 1000)
{
    $errorCode .= "0"; // We need five digits after prefix

    if($id < 100)
        {
            $errorCode .= "0"; // We need five digits after prefix
            if($id < 10)
            {
                $errorCode .= "0" . $id;                
            }
            else
                $errorCode .= $id;
        }
    else
        $errorCode .= $id;

}
else
    $errorCode .= $id;
}
else
    $errorCode = $id;

return $primaryPrefx . "" . $prefix . "-" . $errorCode;
}


 echo getFrom(1568110); // Gives AP-68110
 ?>

Valid for ids < 67599999

And the Code => id function

function getIdFromCode($code)
{
   $prefixes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $id = 0;
   $id += strrpos($prefixes, $code[0]) * 260000; // first prefix
   $id += strrpos($prefixes, $code[1]) * 100000; // second prefix
   $id += intval(substr($code, 3)); // AA- is removed
   return $id;
}

echo getIdFromCode("AP-68110"); // Gives 1568110
Comments