0

I have a list of numbers between 1-20,000. I wish to insert all of these numbers randomly into a table and only once. How can I accomplish this?

For example with 1-10, they would be inserted in the below order, not 1, 2 , 3, 4

9 3 5 1 2 4 6 ..etc

2 Answers2

0

Use shuffle()

$arr = <numbers 1-20K>

shuffle($arr);

<code to insert into sql>
evan
  • 12,307
  • 7
  • 37
  • 51
0

you can use Knuths or Floyds algorithm to achieve this and then store all the numbers in the database. Read this SO question for both the implementation:

Unique random numbers in an integer array in the C programming language

One tip, make sure you dont save into the database for every number generated, you should batch your inserts.

Community
  • 1
  • 1
Baz1nga
  • 15,485
  • 3
  • 35
  • 61
  • Thanks for the tip, I was going to insert one by one. What is the limit on the amount you can insert in a batch? – John Norris May 06 '12 at 08:16
  • the max number of inserts depends on the setting of the MAX_ALLOWED_PACKET variable. If you create a packet that is too large exceeding this value you will run into problems – Baz1nga May 06 '12 at 08:25