Random Account Number Generation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Random Account Number Generation

Post by Nay »

Here's what I've wrote so far:

Code: Select all

<?php
$numbers = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");

for($i=0;$i<9;$i++) {

$number = array_rand($numbers, 1);
$rand_acc .= $number;

}

$q = "SELECT * FROM customers WHERE acc_no = '$rand_acc'";
$r = mysql_query($q, $connection);
if(mysql_num_rows($r) == "0") {
return TRUE;
} else {
return FALSE;
}
?>
Okay, so that'll work fine. But what would I do if the account number generated matched another one and returened false? How can I put into a loop and keep on generating and checking until I get a valid number.

Though it might be impossible to get a duplicate, I just wouldn't want to take risks in having two different accounts with the same number.

-Nay
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

mabe something like this? it would loop until it found a number that didnt match a row in the db.

Code: Select all

<?php
$numbers = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); 


while($valid_acc == false){

  for($i=0;$i<9;$i++) { 
    $number = array_rand($numbers, 1); 
    $rand_acc .= $number; 
  } 

  $q = "SELECT * FROM customers WHERE acc_no = '$rand_acc'"; 
  $r = mysql_query($q, $connection); 
  if(mysql_num_rows($r) == "0") { 
    return TRUE; 
  } else { 
    $valid_acc = FALSE; 
  } 

}
?>
Nay
Forum Regular
Posts: 951
Joined: Fri Jun 20, 2003 11:03 am
Location: Brisbane, Australia

Post by Nay »

OMG! Yes! haha........

Thanks, I've been stuck with for loops for too long.

-Nay
Post Reply