0

I have a script which gets a random number for a registry info, however, the best way I know how to verify if the number is not use, is like this:

$pin = rand(10000, 99999);

$lookforpinsql=mysql_query("SELECT `pin` FROM `db_registery` WHERE `pin` = ".$pin);
$countpin=mysql_num_rows($lookforpinsql);
if ($countpin > 0) { $pin = rand(10000, 99999); }

$lookforpinsql=mysql_query("SELECT `pin` FROM `db_registery` WHERE `pin` = ".$pin);
$countpin=mysql_num_rows($lookforpinsql);
if ($countpin > 0) { $pin = rand(10000, 99999); }

$lookforpinsql=mysql_query("SELECT `pin` FROM `db_registery` WHERE `pin` = ".$pin);
$countpin=mysql_num_rows($lookforpinsql);
if ($countpin > 0) { $pin = rand(10000, 99999); }

I look for it on my dbase 3 times to ensure its not already use, is there a better way?

Barranka
  • 20,547
  • 13
  • 65
  • 83
  • 3
    Please, [don't use `mysql_*` functions in new code](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). *They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation)*. See the [red box](http://uk.php.net/manual/en/function.mysql-connect.php)? Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which. – Jay Blanchard Oct 01 '14 at 17:34
  • 4
    Random and unique are two different things. There is most likely some problem in your concept. A pin does not need to be unique. Even more, it should not be. In contrary, an ID needs to be unique, but not random. An ID can be generated from sql including ensuring that it is unique (that's the purpose of an ID). – Daniel S. Oct 01 '14 at 17:37
  • 2
    Pre-populate a table with unique random PINs. Allocate from there. – tadman Oct 01 '14 at 17:39
  • Assuming there is a good reason for non-sequential random pins... at a minimum, you could put that repetitive code in a while loop... that way it will keep trying until it finds an unused pin (in case it hits a match 3 times in a row). Another idea would be to query a range of (pin - 10) to (pin + 10) -- that way you could do a single query and look to see if there are any holes near the number you just randomized. However those could all be taken as well... still needing another query. – DragonYen Oct 01 '14 at 17:43
  • I was thinking pretty much what tadman is suggesting. Create a table with all possible pins, get one at random from the table and mark it as used or delete it. However, I will say that I don't know why one would need to assign keys like this. – Jonathan Kuhn Oct 01 '14 at 17:44

0 Answers0