Generating unique random strings and pasting into db

I want to write a php function that will create 50,000 unique random alphanumeric strings of length 4 and paste it into the db table. How can i do this?

+3
source share
4 answers
for($i = 0; $i < 50000; $i++)
    $pdo->exec("INSERT INTO table_x (the_string) VALUES (UUID());");

As described here

Edit: alternative insertion method (alternating dashes)

for($i = 0; $i < 50000; $i++)
    $pdo->exec("INSERT INTO table_x (the_string) VALUES (REPLACE(UUID(), '-', ''));");

Edit is worth mentioning:

Inside a single server, UUIDs encode the geographic location and exact time, as well as random sha-1 values.

Thus, the probability of a collision exists only on individual servers (for example, when combining their data sets).

Until we overflow the capacity of geo-time intervals, we are guaranteed not to create duplicate values ​​locally.

( ) UUID (16) ( ) .

+4

- , , , . .

function GenCodes($howmany=50000) {

 $charset = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
 $cl = strlen($charset);
 $codelength = 4;
 $result = array();
 $code = array();
 $lastchar = "";

 for ($x = 1; $x <=$howmany; $x++) {
    for ($i=1; $i<=$codelength; $i++) {
        while(($l = rand(1,$cl-1)) == $lastchar)
            ;
        $code[$i] = $charset[$l];
        $lastchar = $l;
    }
    $code = implode($code);
    $result[$x] = $code;
    $code = "";
    $lastchar = "";
  }
  return $result;
}

, .

function SaveCodes($codes) {
 global $dbHost, $dbPort, $dbUser, $dbPass, $dbName;
 $insctr = 0;
 $db = new db($dbHost, $dbPort, $dbUser, $dbPass, $dbName);
 foreach($codes as $code) {

    $sql = "select code_id from codes where code_code='".$code."'";

    $result = $db->Query($sql);
    if ($db->NumRows() == 0) {  // don't generate an in-use code
        $sql = "insert into codes (code_code) values ('".$code."')";
        $result = $db->Query($sql);
        if ($result) {
            $insctr++;
        }
    }
 }
}
+2

100- . 0, 1,..., A,..., Z,..., a,..., z 62 , 38 - , Á á É é Ó Ö Ö ö Ő ő Ú ú Ű ű .. 100 . 0000 , 1 2000 10. ( 100) . , ( 1 2000) . , .

You should also create batches for insertion, because it is better to have 50 inserts with 1000 rows to insert each of them in order to have 50,000 database queries.

+1
source

All Articles