I want to create a script that users can use to generate a pin with, following registration of an email. The pin needs to be 6 digits long and unique; no two users can have the same pin.
I have the following code, however haven't been able to progress beyond being stuck in an indefinite loop. As more pins are used, the probability of looping the while() function increases. Does any one have any idea of a more elegant solution to this?
Users use their pins to access free services from the website. There is no failure of the service if a user guesses another pin, but it would disrupt the user experience.
If possible, I'd like to distribute the PINs in such a way that statistically the probability of guessing a pin is negligable.
<?php
if($_POST['srSubmit'] && $_POST['srEmail'] && $_POST['srPass']) {
$conn = mysqli_connect('localhost','root','','db_test');
while(1) {
$pin = rand(111111,999999);
$sel = mysqli_query($conn,"SELECT * FROM formusers WHERE pin = '$pin'");
if(mysqli_num_rows($sel) != 0) { continue; }
mysqli_query($conn,"INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysqli_affected_rows($conn)!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
}
?>
<form method="POST" action="">
<input type="email" name="srEmail" value="" placeholder="Email" /><br />
<input type="password" name="srPass" value="" placeholder="Password" /><br />
<input type="submit" name="srSubmit" value="Register" />
</form>