YannBergonzat

PHP Unique Key Generator

Jan 28th, 2015
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.33 KB | None | 0 0
  1. /**
  2.  * Generates a unique key
  3.  * Less than one chance over 1.343646e+111 to bump into an existing key. If it happens, it just generates another key.
  4.  * @param PDO $db        : the PDO instance
  5.  * @param int $length    : the length of the generated key
  6.  * @param string $table  : the table to check for the existing keys
  7.  * @param string $column : the column in $table that contains the key
  8.  * @return string        : the generated unique key
  9.  */
  10. function generateUniqId($db, $length, $table, $column) {
  11.     $query = null;
  12.     $key = '';
  13.     $chars = array(
  14.         'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  15.         'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  16.         '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  17.     );
  18.  
  19.     do {
  20.         while (strlen($key) < $length) {
  21.             $key .= $chars[rand(0, count($chars))];
  22.         }
  23.  
  24.         $query = $db->prepare('SELECT * FROM :tablename WHERE :keyname = :keyvalue');
  25.         $query->execute(array(
  26.             'tablename' => $table,
  27.             'keyname' => $column,
  28.             'keyvalue' => $key,
  29.             'length' => $length
  30.         ));
  31.     } while ($query->rowCount() > 0);
  32.  
  33.     return $key;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment