Search code examples
phpmysqlauto-incrementuniqueidentifier

creating unique user hash for autoincrement field


So in this app, we have a user id which is simple auto-increment primary key. Since we do not want to expose this at the client side, we are going to use a simple hash (encryption is not important, only obfuscation).

So when a user is added to the table we do uniqid(). user_id. This will guarantee that the user hash is random enough and always unique.

The question I have is, while inserting the record, we do not know the user id at that point (cannot assume max(user_id) + 1) since there might be inserts getting committed. So we are doing an insert then getting the last_insert_idthen using that for theuser_id`, which adds an additional db query. So is there a better way to do this?


Solution

  • A few things before the actual answer: with latest version of MySQL which uses InnoDB as default storage engine - you always want an integer pk (or the famous auto_increment). Reasons are mostly performance. For more information, you can research on how InnoDB clusters records using PK and why it's so important. With that out of the way, let's consider our options for creating a unique surrogate key.

    Option 1

    You calculate it yourself, using PHP and information you obtained back from MySQL (the last_insert_id()), then you update the database back.

    Pros: easy to understand by even novice programmers, produces short surrogate key.

    Cons: extremely bad for concurrent access, you'll probably get clashes, and you never want to use PHP to calculate unique indices required by the database. You don't want that option

    Option 2

    Supply the uniqid() to your query, create an AFTER INSERT trigger that will concatenate uniqid() with the auto_increment.

    Pros: easy to understand, produces short surrogate key.

    Cons: requires you to create the trigger, implements magic that's not visible from the code directly which will definitely confuse a developer that inherits the project at some point - and from experience I would bet that bad things will happen

    Option 3

    Use universally unique identifiers or UUIDs (also known as GUIDs). Simply supply your query with surrogate_key = UUID() and MySQL does the rest.

    Pros: always unique, no magic required, easy to understand.

    Cons: none, unless the fact that it occupies 36 chars bothers you.

    You want the option 3.