-1

Let's say I have given a user an access code. I have generated the code in php and would like to insert this random access code into the database, however it has to be unique to that user. So, when I have created the code and it checks to see if that code already exists in the database, if it returns true (as in, it is already existing), I want the script to "go back" or "loop" until it generates one that doesn't already exist.

I know how to generate the code, and how to insert into the mysql database. My question is simply, how would I go about writing the "loop" portion?

Keegan
  • 19
  • 2
  • 1
    Perhaps you should look into a recursive function. http://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php – CD Brian May 05 '15 at 02:55
  • 1
    Can you not simply have a loop do this? While in database is true? – Jonathan Holland May 05 '15 at 02:56
  • 1
    why not just generate unique codes right off the bat? many ways to do this, rather than regenerating all the time and be a waste of time, *at best*. All this using a UNIQUE constraint. – Funk Forty Niner May 05 '15 at 02:57

4 Answers4

1

Why not generate something unique with a quality method instead of making a code, and checking if its already in the database?

Do something like,

hash($username)

So, aslong as the "username" is unique, the code will be unique as well.

P.S : hash, I just mentioned in the code, can be any hashing algorithm. Md5(not that recommend),Sha1 or whatever.

Kishor Kurian
  • 175
  • 1
  • 6
0

You can end a loop with break. So loop, then when the variable is false -- meaning you have a unique code, stop the loop with break.

while {
   ...
   if ($variable === false) {
      break;
   }
}

Or even:

$variable = true;
while ($variable) {
   ...
   $variable =  isItInTheDatabase();
}

Which would stop the loop once $variable is false, null, or 0.

Devon
  • 32,773
  • 9
  • 61
  • 91
0
do {
$code = generate_a_random_string();
} while(mysql_num_rows(mysql_query("select * from table where code = '".mysql_real_escape_string($code)."'")))

// Insert the code
Alex83690
  • 667
  • 8
  • 26
0

Its very simple generate really a unique that can't be repeated by code generator, you can use timestamp and extra character.

Varun Naharia
  • 5,100
  • 9
  • 47
  • 81