Hello,

Lets say I have a users Database.
When the user registers, it assigns a random id to the user using the mt_rand(); function.

What if there is a slight chance that there would be already the id of that user in the db. How can I prevent this from happening? Besides using AI in the db?

Thanks in advance! :)

Dani AI

Generated

Short answer: let the database enforce uniqueness. is right that a DB-managed key (auto-increment/sequence) is the simplest, safest way to guarantee no duplicate IDs. The application should not try to invent unique numeric primary keys by fetching the current max and adding one — that pattern leads to race conditions under concurrent registrations.

If you want non-sequential or hard-to-guess public identifiers, keep an internal numeric primary key for joins and indexing, and add a separate indexed column for the public token. Generate that token with a cryptographically secure method and place a UNIQUE constraint on the column so the database will reject any collision. On insert, catch the duplicate-key error and retry generating a new token. For guidance on database-managed numbering see the MySQL auto-increment documentation and for secure token generation see PHP’s cryptographic random functions.

Notes and trade-offs: random tokens (UUIDv4 or securely generated byte sequences) make guessing much harder but cost more storage and slower indexes than compact integers. If you need global uniqueness across multiple servers, choose UUIDs or a coordinated ID generator rather than ad-hoc random numbers. Conversely, if you only need a simple internal key for relations, a DB auto-increment or sequence is the cleanest solution.

References:

Recommended Answers

All 2 Replies

Normally for a registration system you start at 0 and count up from that as each user is registered. So for example in the database you could have auto incremental or you could get php to fetch the highest number and add one to that. Hope that helps :)

Okay. Thanks, I think I will just start @ 0 then ;) THanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.