Do you need to use rand to generate a random number and then go to the database to query whether there is such a number? It seems a little time-consuming. Is there any other way? Do you need to use rand to generate a random number and then go to the database to query whether there is such a number? It seems a little time-consuming. Is there any other way?
Reply content:
Do you need to use rand to generate a random number and then go to the database to query whether there is such a number? It seems a little time-consuming. Is there any other way?
There are two solutions.
1. If you only use php instead of a databaseTimestamp + Random Number
Is the best method, and does not repeat;
2. If you need to use a database, you also need to associate this id with some other data. Then, an AUTO_INCREMENT (auto-increment) attribute is assigned to the table id in the MySQL database. Each time a data entry is inserted, the id is automatically + 1, and thenmysql_insert_id()
OrLAST_INSERT_ID()
Returns the auto-increment id.
1. If the random range is large, it is difficult to duplicate random numbers.
2. OK. We also want to repeat it. Then we will add an index to the random number field of the database table. The time complexity is O (LogN)
The timestamp is unique, and the final value obtained by adding a fixed value to the timestamp is also unique. It is better not to compare data with databases, which is a waste of time.
Set a range of numbers to be retrieved, and put all data into the database.
Each time an id is issued, it is marked as "used" in the database 」.
A random id not marked as "used" when sending the code, and then the id is returned.
Timestamp + random number.
Simplest: Obtain the uniqid with the timestamp
There is already a ready-made solution to this problem. The php uuid extension can perfectly solve this problem. This extension can generate a unique full digital signature .. If you do not use composer, refer to composer
Timestamp + Random Number