-1

How to make a random string unique to the string in the column below?

enter image description here

<?php
$n=10;
function getName($n) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';

    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}

echo getName($n);
?>
6
  • Does this answer your question? PHP/MySQL - Best way to create unique random string? Commented Mar 6, 2022 at 12:16
  • Is string column already defined as unique? Commented Mar 6, 2022 at 12:18
  • Yes, But sometimes it will randomize the already existing string causing an error when saving. Commented Mar 6, 2022 at 12:28
  • You mean you randomize the random string? Not sure I know what you mean.. whats the error? Commented Mar 6, 2022 at 12:34
  • If I want to randomize one number from "1,2,3", But there is already a row with the value 2 in the "String" column, the random value must be either 1 or 3. Commented Mar 6, 2022 at 12:40

2 Answers 2

0
<?php
    $n = 10;
    function getName($n) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $n; $i++) {
            $index = rand(0, strlen($characters) - 1);
            $randomString .= $characters[$index];
        }
        return $randomString;
    }
    function getUniqueString($length, $dbConnection){
        $string = getName($length);
        $count  = $dbConnection->query("SELECT * FROM TABLE_NAME WHERE string='$string')")->num_rows;
        while($count != 0){
            $string = getName($length);
            $count  = $dbConnection->query("SELECT * FROM TABLE_NAME WHERE string='$string')")->num_rows;
        }
        return $string;
    }

    echo getUniqueString($n, $dbConnection);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

If the table name is "test', how should I add the table name?
Replace TABLE_NAME with what your actual table name is.
0

You can use openssl_random_pseudo_bytes() or random_bytes() PHP fonction to generate random strings.

You can also rely on MySQL to generate uniq IDs :

INSERT INTO mytable (alphaID) VALUES (REPLACE( UUID(), '-', '' )); 

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.