2

I need to generate a random alphanumeric string that is unique to all values in a specific column in one of my tables in phpmyadmin. Also, I need it to be 20 characters long. There are many questions like this already posted but I didn't see any that needed a string unique to a column in phpmyadmin.

So how would I do this in php?

2
  • 3
    Generate a random string using any of the methods in the related questions, check whether it's already in use in the column. Repeat until you get one that's not in use. Commented Oct 7, 2013 at 19:54
  • AFAIK, Phpmyadmin is not a database engine. If you want to generate random strings with a certain character length, there is a lot of information about this online. You would have to check each time to see if that value is unique in the column. Commented Oct 7, 2013 at 19:55

3 Answers 3

5

Something like this:

function isToken($token)
{
    if (isset($token) && $token) {

        //verification values in BD
        $query = "SELECT id FROM table WHERE token='$token'";
        $sql = mysql_query($query);
        if (mysql_num_rows($sql) > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function generateUniqueToken($number)
{
    $arr = array('a', 'b', 'c', 'd', 'e', 'f',
                 'g', 'h', 'i', 'j', 'k', 'l',
                 'm', 'n', 'o', 'p', 'r', 's',
                 't', 'u', 'v', 'x', 'y', 'z',
                 'A', 'B', 'C', 'D', 'E', 'F',
                 'G', 'H', 'I', 'J', 'K', 'L',
                 'M', 'N', 'O', 'P', 'R', 'S',
                 'T', 'U', 'V', 'X', 'Y', 'Z',
                 '1', '2', '3', '4', '5', '6',
                 '7', '8', '9', '0');
    $token = "";
    for ($i = 0; $i < $number; $i++) {
        $index = rand(0, count($arr) - 1);
        $token .= $arr[$index];
    }

    if (isToken($token)) {
        return generateUniqueToken($number);
    } else {
        return $token;
    }
}


$uniqueToken = generateUniqueToken(20);
Sign up to request clarification or add additional context in comments.

1 Comment

return false; // <-- forgot semi-colon
2

There's no way to get unique random in a MySQL table automatically. You must create a unique random text in PHP and find it in the MySQL table, and if it exists generate it again.

protected function generateToken($length=6){
    return substr(str_shuffle('abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ1234567890'),rand(0,60-$length),$length);
}

Comments

1

I think I could make it super simple:

echo md5(time());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.