Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Generates a unique key
- * Less than one chance over 1.343646e+111 to bump into an existing key. If it happens, it just generates another key.
- * @param PDO $db : the PDO instance
- * @param int $length : the length of the generated key
- * @param string $table : the table to check for the existing keys
- * @param string $column : the column in $table that contains the key
- * @return string : the generated unique key
- */
- function generateUniqId($db, $length, $table, $column) {
- $query = null;
- $key = '';
- $chars = array(
- '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',
- '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',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
- );
- do {
- while (strlen($key) < $length) {
- $key .= $chars[rand(0, count($chars))];
- }
- $query = $db->prepare('SELECT * FROM :tablename WHERE :keyname = :keyvalue');
- $query->execute(array(
- 'tablename' => $table,
- 'keyname' => $column,
- 'keyvalue' => $key,
- 'length' => $length
- ));
- } while ($query->rowCount() > 0);
- return $key;
- }
Advertisement
Add Comment
Please, Sign In to add comment