Does php generate a unique numeric id like a QQ number?

Source: Internet
Author: User
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 NumberIs 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.