M
M
MainMaster2020-05-06 12:13:28
MySQL
MainMaster, 2020-05-06 12:13:28

Generation of short unique keys in mysql how to implement?

Hello, I have a table like this in a database

CREATE TABLE links (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
url VARCHAR(2048) NOT NULL,
short_key VARCHAR(10) NOT NULL
);


I want to drop the id field and use short_key instead, which will play the same role.
short_key is a case-sensitive field, it must be PRIMARY KEY and, when inserted, it must be automatically
generated with a string length of 1 to 10 characters, which includes only Latin letters.

Can you tell me how to make the short_key generated automatically with a check for uniqueness according to the above criteria?

UPDATE: I forgot to say that the short_key target is needed so that smart-ass users cannot iterate through all records by id by changing the id in the link.
Thanks in advance for your time!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Adamos, 2020-05-06
@MainMaster

Leave the database alone. She has nothing to do with this task at all.
All you need is reversible encryption with your ID key - so that the user sees the encrypted string, and you can get the ID back from it. That's all.
PS However, special encryption is not required for such a purpose. Collect the string {N1}{N2}{N3}, where N1 and N2 are random numbers of a given length, and N3 = (N1 * N2 + ID) XOR C - here is the finished short_key, from which we get back ID = (N3 XOR C ) - (N1*N2)

P
Peter, 2020-05-06
@petermzg

Since your goal is "needed so that smart-ass users cannot sort through all the records by id by changing the id in the link."
Leave the ID as AUTOINCREMENT INTEGER and just add one more field with a "salt", for the char(3) type example, where when inserting and store the random string value.
When you generate a URL, then make it according to the pattern ID + "-" + SALT, which will help you achieve the desired goal.

P
Pavel, 2020-05-06
@PavelFokeev

SQL does not know how to generate unique rows. Generate with php:unique();

D
d-stream, 2020-05-06
@d-stream

UUID() - very long?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question