This is a follow-up question to a question I posted here.
I am using the following code to give users a unique id:
function NewGuid() {
$s = strtoupper(uniqid(rand(),true));
$guidText = substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4). '-' . substr($s,16,4). '-' . substr($s,20); return $guidText;
}
$Guid = NewGuid();
echo $Guid;
$alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
function base_encode($num, $alphabet) {
$base_count = strlen($alphabet);
$encoded = '';
while ($num >= $base_count) {
$div = $num/$base_count;
$mod = ($num-($base_count*intval($div)));
$encoded = $alphabet[$mod] . $encoded;
$num = intval($div);
}
if ($num) $encoded = $alphabet[$num] . $encoded;
return $encoded;
}
function base_decode($num, $alphabet) {
$decoded = 0;
$multi = 1;
while (strlen($num) > 0) {
$digit = $num[strlen($num)-1];
$decoded += $multi * strpos($alphabet, $digit);
$multi = $multi * strlen($alphabet);
$num = substr($num, 0, -1);
}
return $decoded;
}
echo base_encode($Guid, $alphabet);
So, if a id that is generated is already in use, i want this code to be able to repeat until a completely new id is generated and entered into the database. IN addition i am new to programming, so please feel free to elaborate 😉
Any thoughts? Thanks.
Super easy.
You have 3 functions.
One – main generate guid function.
Two – Sub generate guid function.
Three – Sub insert guid function.
Sub generate function:
Does the actual generation, returns a guid.
Sub insert function:
Attempts to insert guid into the database. Returns false/null on failure. True/data on success.
Main function:
In a loop:
Call subfunction to get a guid.
Call subfunction to insert in the database where the guid is a unique or primary key.
On failure, restart the loop.
Success exits the loop and returns the guid.
Example: