Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique, unpredictable, 12 digit, integer id

Tags:

php

random

mysql

How would I go about generating this... I want to keep my primary key sequential and have a 12 digit unique pin generated for each new object added to the database.

The reason it cant just be autoincrement is i don't want the sequential numbers to be easily guessable.

It needs to be integer numbers, because I'm going to have verification codes that need to be dialed on a phone pad.

like image 505
michael Avatar asked Aug 25 '11 17:08

michael


3 Answers

Use a concatenation of a unique incremented number and a randomly generated number.

The unique incremented number ensures that the result is unique, and the randomly generated number makes it hardly guessable.

This is simple and guaranteed to have no collision (1). The result is incremental, partly random, and non-predictable (provided that the random number part is generated with a good PRNG).

(1): You have to either pad id and random with zeros, or to separate them with some non-digit character.

With a MySQL db, this translates to:

CREATE TABLE foo (
    id int not null auto_increment,
    random int not null,
    ...
    primary key (id)
);
like image 176
Arnaud Le Blanc Avatar answered Sep 25 '22 21:09

Arnaud Le Blanc


Maybe you can use UUID_SHORT(). Not 12 digits long, but still could be a viable option:

mysql> select uuid_short();
+-------------------+
| uuid_short()      |
+-------------------+
| 22048742962102272 |
+-------------------+

So:

INSERT INTO `table` (`id`, `text`) VALUES (UUID_SHORT(), 'hello world!');

Note: If you really want to have exactly 12 digits, then don't even try to substring the result, if would not ensure the uniqueness of the identifier and may cause collisions.

like image 28
netcoder Avatar answered Sep 22 '22 21:09

netcoder


<?php 
$allowed_characters = array(1,2,3,4,5,6,7,8,9,0);
for($i = 1;$i <= 12; $i++){
    $pass .= $allowed_characters[rand(0, count($allowed_characters) - 1)];
}
echo $pass;
?>

demo: http://sandbox.phpcode.eu/g/c0190/4

like image 39
genesis Avatar answered Sep 24 '22 21:09

genesis