-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);
?>
Noso Sanas
  • 51
  • 7

2 Answers2

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);
?>
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(), '-', '' )); 
Alaindeseine
  • 3,260
  • 1
  • 11
  • 21