1

I need to insert a 6 digit key into my database. I can't figure out how to do the loop part. If the key is in use I need to keep generating a new key and checking it to make sure its not in use.

$row=mysql_fetch_assoc(mysql_query("SELECT count(*) as numrecords FROM id WHERE id='".$generated_id."'"); 
if ($row['numrecords'] >= 1)
{ 
//key is in use generate new key and loop to make sure its not in use
} 
else 
{ 
//insert key
}
mysql_close();

Thanks

8
  • @R3dBu77: Any reason why you can't make that database field a unique index? Commented Dec 20, 2010 at 0:57
  • Are you trying to replace an auto-increment ID? Commented Dec 20, 2010 at 0:57
  • Why aren't you using an AUTO_INCREMENT column so there's no searching? (Assuming that's what you're after, a unique primary key) Commented Dec 20, 2010 at 0:58
  • elusive yes. i cant use auto-icrement because i cant have the numbers in order. 1,2,3,4,5 etc. Commented Dec 20, 2010 at 0:59
  • 1
    Its for a video site. Video.php?id=. The uploader has the option to pick unlisted. If the pick unlisted the video will not be posted on the site but anyone with the id can view it. If I use auto-increment the id's would be sequential. A person could just keep adding 1 to the id and view every video. Commented Dec 20, 2010 at 1:05

3 Answers 3

2

I'd add a UNIQUE key constraint on the column:

ALTER TABLE id ADD UNIQUE id;

Then you can use this PHP code:

while (1) {
  // generate ID
  $sql = "INSERT....";
  $result = mysql_query($sql);
  if ($result !== false) { break; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very sensible, I would suggest an edit to make clear that the SQL in the loop is an INSERT.
1

How about this:

do {
    $row = mysql_fetch_assoc(mysql_query("SELECT count(*) as numrecords FROM id WHERE id='".$generated_id."'");
    if ($row['numrecords'] >= 1)
    { 
        //key is in use generate new key and loop to make sure its not in use
        // regenerate $generated_id
    }
} while ($row['numrecords'] >= 1);

//insert key

mysql_close();

Or to clean things up a bit:

while (mysql_result(mysql_query("SELECT 1 FROM id WHERE id='".$generated_id."'"))) {
   $generated_id = generateKey();
}

// insert key

mysql_close();

Comments

0

If you are using such code to generate loop, simply put a test at the beginning:

while(true)
$row=mysql_fetch_assoc(mysql_query("query goes here"));
if($row) { continue; }
// rest of code

Don't forget to add some break; when code reach too many iterations or you found non-existent sequence.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.