Jump to content

Generate a random number & check DB to see it is unique


playaz

Recommended Posts

Hi guys,

I have a registration form that once submitted inserts the values into a mysql db. Its a registration form for a trade account (eCommerce site) - basically once a company applies for a trade account, i'd like an Account Number to be generated automatically however obviously this needs to be unique.

So ideally i'd would like it to randomly generate an 8 digit number and then check the database to ensure it isn't already in use.

Can anyone assist me on this thanks :)
Link to comment
Share on other sites

you could loop random number generation checked against the database.

[code]
$loop=true;
while($loop) {
  $acct_num = rand(10000000,99999999);
  if(!mysql_query("SELECT * FROM `table` WHERE `account_number` = '".$acct_num."' LIMIT 1")) $loop=false;
} // when found, loop ends, and $acct_num retains a value you can use later.
[/code]

Some mysql expert should have a better mysql solution -- which would be much faster -- but the above code still works.
Link to comment
Share on other sites

I would get all of the current id numbers in the database, store them to a temporary array, then generate the random numbers until you find one not in the temporary array.

Something like:
[code]<?php
$q = "select acct_num from your_table";
$rs = mysql_query($q);
$tmp = array();
while ($rw = mysql_fetch_assoc($rs))
      $tmp[] = $rw['acct_num'];
$new_acct_num = rand(10000000,99999999);
while (in_array($new_acct_num,$tmp)) $new_acct_num = rand(10000000,99999999);
echo $new_acct_num;
?>[/code]

There is a slim possibility that this code will produce a duplicate number if more than one new account is processed at the same time (before the database is updated with the new number).

Is there any reason why you can't use an autoincrement field?

Ken
Link to comment
Share on other sites

  • 1 year later...
[quote]There is a slim possibility that this code will produce a duplicate number if more than one new account is processed at the same time (before the database is updated with the new number).
[/quote]

This can be solved using inodb tables along with transactions.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.