PHP short unique ID generation using auto_increment?

后端 未结 8 1480
自闭症患者
自闭症患者 2021-02-04 17:14

I would like to generate a short, unique ID without having to check for collisions.

I currently do something like this, but the ID I currently generate is random and che

8条回答
  •  失恋的感觉
    2021-02-04 17:51

    You could probably generate a MD5 hash of the current datetime/random number and truncate it to the length you need (5-8 characters) and store it as the id field.

    If you are using storing this information in a database, you don't need to use a for loop to do the collision check, but you could just do a select statement - something like

    SELECT count(1) c FROM Table WHERE id = :id
    

    where :id would be the newly generated id. If c is greater than 0 then you know it already exists.

    EDIT

    This may may not be the best way to go about it. But I'll give it a shot, so I guess what you need is someway of converting a numbers into a unique short string and that is not in sequence.

    I guess as you said, base64 encoding already does the number to short string conversion. To avoid the sequence problem you could have some mapping between your auto-generated id's to some "random" value (unique mapping). Then you can base64 encode this unique value.

    You could generate this mapping as follows. Have a temporary table store values from 1 - 10,000,000. Sort it in random order and store it into you Map table.

    INSERT INTO MappingTable (mappedId) SELECT values FROM TemporaryTable ORDER BY RAND()
    

    Where MappingTable would have the 2 fields id (your auto-generated id would look up against this) and mappedId (which is what you would generate the base64 encoding for).

    As you get closer to 10,000,000 you could rerun the above code again and change the values in the temporary table with 10,000,001-20,000,000 or something like that.

提交回复
热议问题