Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting random characters to MYSQL Database

Tags:

random

mysql

I want to add 100 entry to users table numbers field, random characters length is 10, all entry should be unique as well. How can i achieve this using MYSQL query code ?

Or do i need to use PHP ?

Help me with code snippets please. Thanks.

like image 788
spotlightsnap Avatar asked Nov 30 '22 06:11

spotlightsnap


2 Answers

in mysql u can do like :

insert into table ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , .........

..............

in php see this 2 links :

Short unique id in php

What is the best way to generate a random key within PHP?

like image 127
Haim Evgi Avatar answered Dec 15 '22 04:12

Haim Evgi


That may create duplicates and it's too long. This is 10 char long:

UPDATE users SET numbers = SUBSTRING(MD5(RAND()) FROM 1 FOR 10)

However, you could still get duplicate values.

So you could put a unique restraint on your column. Then try the update. If there are duplicates, you will get an error. Then just try again. You only have 100 entries, so it's probably fine.

Is this for passwords?

If so, I'd recommend encrypting the value. Of course you then have the problem of not knowing what the value is. So you could create a temporary table, insert the random values in there. Then encrypt the values as they are inserted from the temp table into the real table. You can then use the temp table for reference (giving the users their passwords, etc). Hope that helps.

like image 28
d-_-b Avatar answered Dec 15 '22 06:12

d-_-b