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

后端 未结 11 2052
清酒与你
清酒与你 2020-12-02 11:15

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

11条回答
  •  执笔经年
    2020-12-02 12:04

    You have two approaches:

    The first, suggested in other answer, is to create a random number (using mt_rand() ) and check it's not in the database. If it is in the database, regnerate and try again. This is simplest if you are generating a single number - see other answers for code. But if you are gnerating more that 50% of the numbers it will be very slow and inefficient.

    If ou want a lot of numbers, the alternative is to populate a database with all the records and have a column "picked". Run a query to find how many are "not picked" and then find a random number between 0 and the number "not picked". Then run the SQL query to get the number in that position (where not picked, use LIMIT in mysql) and mark as picked. A bit convoluted, it's more work and less efficient if you only want a few numbers, but will be much better when you want to get more that 50% (estimate) of the numbers.

    Note: you can make it more efficient by storing the count selected locally and running a few less queries.

提交回复
热议问题