Monday 16 July 2018

Generating a Unique ID Using PHP and MySQL

Generating a Unique ID Using PHP and MySQL

A recent e-commerce project I was working on required me to generate a unique order reference number containing both letters and numbers for every new order placed. Generating a unique reference was easy, but what if the generated output already existed in the database? Wouldn’t be very unique now would it!
After a few minutes deliberating over the best way to go about this I came up with the below:

  1. // The length we want the unique reference number to be  
  2. $unique_ref_length = 8;  
  3.   
  4. // A true/false variable that lets us know if we've  
  5. // found a unique reference number or not  
  6. $unique_ref_found = false;  
  7.   
  8. // Define possible characters.  
  9. // Notice how characters that may be confused such  
  10. // as the letter 'O' and the number zero don't exist  
  11. $possible_chars = "23456789BCDFGHJKMNPQRSTVWXYZ";  
  12.   
  13. // Until we find a unique reference, keep generating new ones  
  14. while (!$unique_ref_found) {  
  15.   
  16.     // Start with a blank reference number  
  17.     $unique_ref = "";  
  18.       
  19.     // Set up a counter to keep track of how many characters have   
  20.     // currently been added  
  21.     $i = 0;  
  22.       
  23.     // Add random characters from $possible_chars to $unique_ref   
  24.     // until $unique_ref_length is reached  
  25.     while ($i < $unique_ref_length) {  
  26.       
  27.         // Pick a random character from the $possible_chars list  
  28.         $char = substr($possible_chars, mt_rand(0, strlen($possible_chars)-1), 1);  
  29.           
  30.         $unique_ref .= $char;  
  31.           
  32.         $i++;  
  33.       
  34.     }  
  35.       
  36.     // Our new unique reference number is generated.  
  37.     // Lets check if it exists or not  
  38.     $query = "SELECT `order_ref_no` FROM `orders` 
  39.               WHERE `order_ref_no`='".$unique_ref."'";  
  40.     $result = mysql_query($queryor die(mysql_error().' '.$query);  
  41.     if (mysql_num_rows($result)==0) {  
  42.       
  43.         // We've found a unique number. Lets set the $unique_ref_found  
  44.         // variable to true and exit the while loop  
  45.         $unique_ref_found = true;  
  46.       
  47.     }  
  48.   
  49. }  
  50.   
  51. echo 'Our unique reference number is: '.$unique_ref;  
The above code will generate a unique reference number and check it against the database to ensure it doesn’t already exist.  If it does repeat the sequence and try again or, if it is indeed unique, continue with the script.

0 comments:

Post a Comment