How to generate unique random string with ServerConnect

Hi all,

I have a table “pages”, containing columns “id” and “slug”.
User can create a new Page and I need to automatically create a unique “slug” for it. Here is an example:
pages.cc/X1Af9M
“Slug” is 6 chars alphanumeric string. Every page is unique, so duplicates are not allowed.

What is the best and efficient way of doing it on ServerConnect side? How to generate this profile of string and how to ensure uniqueness without shooting duplicate errors to the user.

Use the Cryptographic function server side, SHA256 or whatever you please, select now as the value, and then select now for the salt. Should insure no collisions.

Thanks, Dave, but what if we have limited number of chars, only 6 or even 5, so URL will look like pages.cc/X1Af9M. SHA produces much longer string, which doesn’t fit the requirement.

Simply set the column length to 6 and should work fine, storing only the first 6 characters.

How then it ensures uniqueness?
There will be plenty of hashes with the same 1st six chars, like this:

c0d4763cc646619849b5284921c22c1e1669e2485f9168afbf829eb44f8965c3
c0d476029121b0d2d9457096651bc316307ab14264baf0ec9d774cece136a01d

1 Like

Could always do it at the SQL level instead.

https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_aes-encrypt

You always have a chance on collisions, generate some random string and then check if it is unique, regenerate when not unique.

Random string using timestamp and md5:

{{ TIMESTAMP.md5().substr(0, 6) }}
7 Likes

Thanks, will try this approach!

I want to do the same thing, but I want the random string to contain a mix of upper case letters, lower case letters and numbers - but not other characters such as $, # etc.

@patrick, what function should I use to create that?

the .md5() function only creates numbers and letters a-f.

1 Like

How about using PHP?
<dmx-value id="myNumber" value="<?php echo(rand(100000000,999999999)) ?>"></dmx-value>

Then use some PHP to turn the numbers into letters:

$letter = chr($i+65);
    echo $letter;

You could use a do while loop and pass each number from the rand functions and as you are looping through you can construct a string.