How to Generate Random number without repeat in database using PHP?
In addition to Tushar's answer to make it work when numbers_mst is empty:
SELECT random_num
FROM (
SELECT FLOOR(RAND() * 99999) AS random_num
UNION
SELECT FLOOR(RAND() * 99999) AS random_num
) AS numbers_mst_plus_1
WHERE `random_num` NOT IN (SELECT my_number FROM numbers_mst)
LIMIT 1
NOTE: The other solutions posted will work only if the column is configured as NOT NULL
. If NULL
, it'll just return no results. You can fix the query like this:
SELECT random_num
FROM (
SELECT FLOOR(RAND() * 99999) AS random_num
) AS numbers_mst_plus_1
WHERE random_num NOT IN (SELECT my_number FROM numbers_mst WHERE my_number IS NOT NULL)
LIMIT 1
... The ...WHERE my_number IS NOT NULL
is necessary!
EDIT: I just wanted to mention that I intentionally removed the inner SELECT
's table name because it didn't seme necessary and seemed to break if there was no data in the table yet? However, maybe this was intentionally included? — Please clarify or comment for everyone, thanks.
This is easiest method to build unique code generator without check database, it will save database query execution time.
function unique_code_generator($prefix='',$post_fix='')
{
$t=time();
return ( rand(000,111).$prefix.$t.$post_fix);
}
Enjoy, have a nice coding day..
:)
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:
- Selects random number between 0 - 1 using RAND().
- Amplifies that to be a number between 0 - 99999.
- Only chooses those that do not already exist in table.
- Returns only 1 result.