Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating unique random strings and insering into db

Tags:

php

mysql

I want to write a php a function which will create 50000 unique random alpha numeric string of length 4 and insert it into a db table. how can I do it?

like image 252
S. M. Shahinul Islam Avatar asked Nov 29 '25 16:11

S. M. Shahinul Islam


1 Answers

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

As documented here

Edit: alternative insert manner (striping the dashes)

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

Edit worth mentioning:

Within one single server the UUIDs encode geographic location and precision time, along with sha-1 random values.

Thus the probability of collision only exists within separate servers (for example when merging their data sets).

So long as we don't overflow the capacity of the geo/time slots it is guaranteed to not create duplicate values locally.

As a matter of optimisation (speed of database reads) casting the UUID to a binary(16) field (and having the column in the table to match that datatype) is faster and more compact.

like image 151
Mihai Stancu Avatar answered Dec 02 '25 07:12

Mihai Stancu



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!