Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate Random number without repeat in database using PHP?

Tags:

mysql

I would like to generate a 5 digit number which do not repeat inside the database. Say I have a table named numbers_mst with field named my_number.

I want to generate the number the way that it do not repeat in this my_number field. And preceding zeros are allowed in this. So numbers like 00001 are allowed. Another thing is it should be between 00001 to 99999. How can I do that?

One thing I can guess here is I may have to create a recursive function to check number into table and generate.

like image 812
aslamdoctor Avatar asked Jul 27 '12 00:07

aslamdoctor


People also ask

How do you generate a non repeating random number in PHP?

php $check = array(); function generateNumber() { global $check; $page_no = mt_rand(1,20); $check[] = $page_no; if (count($check) != 1) { foreach ($check as $val) { if ($val == $page_no) { $page_no = mt_rand(1,10); continue; } } return $page_no; } else { return $page_no; } } ?>

How do I generate a random number in PHP?

The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

How do you generate random unique numbers in mysql?

SQL Server has a built-in function that generates a random number, the RAND() mathematical function. The RAND math function returns a random float value from 0 through 1. It can take an optional seed parameter, which is an integer expression (tinyint, smallint or int) that gives the seed or start value.


1 Answers

SELECT FLOOR(RAND() * 99999) AS random_num FROM numbers_mst  WHERE "random_num" NOT IN (SELECT my_number FROM numbers_mst) LIMIT 1 

What this does:

  1. Selects random number between 0 - 1 using RAND().
  2. Amplifies that to be a number between 0 - 99999.
  3. Only chooses those that do not already exist in table.
  4. Returns only 1 result.
like image 88
Tushar Avatar answered Oct 09 '22 16:10

Tushar