Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert unique strings of 8 random characters

Tags:

php

mysql

I'm using PHP and MySQL and I have a table with 3 fields ((ID, Username, PID)).

I want the PID field to contain strings of 8 unique characters.

My solution is to generate the random string in PHP and check if it exists. If it exists then it will generate another string.

Is there any better solution that will save processing time, like a MySQL trigger or something like that?

like image 444
trrrrrrm Avatar asked Dec 18 '25 06:12

trrrrrrm


1 Answers

This will give you a random 8 character string:

substr(str_pad(dechex(mt_rand()), 8, '0', STR_PAD_LEFT), -8);

Found here: http://www.richardlord.net/blog/php-password-security

Or if the username field is unique you could also use:

substr(md5('username value'), 0, 8);

Though it's extremely unlikely, particularly for the md5, neither case guarantees a unique string, so I would probably do something like this:

// Handle user registration or whatever...

function generatePID($sUsername) {
    return substr(md5($sUsername), 0, 8);
}

$bUnique = false;
$iAttempts = 0;

while (!$bUnique && $iAttempts < 10) {
    $aCheck = $oDB->findByPID(generatePID("username value")); // Query the database for a PID matching whats generated
    if (!$aCheck) { // If nothing is found, exit the loop
        $bUnique = true;
    } else {
        $iAttempts++;
    }
}

// Save PID and such...

... which would probably only yield 1 'check' query, maybe 2 in unique cases, and would ensure a unique string.

like image 74
Chris Forrette Avatar answered Dec 19 '25 21:12

Chris Forrette



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!