PHP / MySQL循环帮助

时间:2010-12-20 00:54:58

标签: php mysql

我需要在我的数据库中插入一个6位数的密钥。我无法弄清楚如何做循环部分。如果密钥正在使用中,我需要继续生成一个新密钥并检查它以确保它没有被使用。

$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();

由于

3 个答案:

答案 0 :(得分:2)

我在列上添加了一个UNIQUE键约束:

ALTER TABLE id ADD UNIQUE id;

然后你可以使用这个PHP代码:

while (1) {
  // generate ID
  $sql = "INSERT....";
  $result = mysql_query($sql);
  if ($result !== false) { break; }
}

答案 1 :(得分:1)

这个怎么样:

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();

或稍微清理一下:

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

// insert key

mysql_close();

答案 2 :(得分:0)

如果您使用此类代码生成循环,只需在开头进行测试:

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

不要忘记添加一些休息;当代码达到太多次迭代或你发现不存在序列时。