【问题标题】:If a value already exists in sql database, create new values until a unique one comes up如果sql数据库中已经存在一个值,则创建新值直到出现唯一值
【发布时间】:2019-08-29 16:49:13
【问题描述】:

因为我需要为每个用户生成一个唯一的“id”,所以我需要检查这个随机生成的 id 是否已经存在于数据库中,如果存在,则创建一个新的 id 并重复该操作直到一个唯一的 id被发现。现在,我不知道我这样做是否正确,因为我没有办法检查,谁能告诉我我这样做是否正确,如果没有,我应该改变哪一部分?

这是我的 php 代码:

  $bytes = '15';
  $secondary_id = bin2hex(openssl_random_pseudo_bytes($bytes));
  $stm_reg3 = $conn->prepare('SELECT secondary_id FROM users WHERE secondary_id = :secondary_id LIMIT 1');
  $stm_reg3->bindParam(":secondary_id", $secondary_id, PDO::PARAM_STR);
  $stm_reg3->execute();
  $row3 = $stm_reg3->fetch(PDO::FETCH_ASSOC);
if ( ! $row 3) {
while ( ! $row3) {
  $secondary_id = bin2hex(openssl_random_pseudo_bytes($bytes));
  $stm_reg3->execute();
}
}

【问题讨论】:

  • 为什么需要这样做?这听起来像个可怕的主意。
  • @devlincarnate 你如何建议他生成一个唯一的随机字符串?
  • @Barmar:Google for php generate unique random string,开始...并考虑让 db 处理“id”生成而不是 php。
  • 如果您自己滚动,请注意比赛条件。

标签: php pdo


【解决方案1】:

每次通过while 循环时,您都需要在$stm_reg3->execute() 之后调用$stm_reg3->fetch()。您可以将它们合并为一个调用。

$bytes = '15';
$secondary_id = bin2hex(openssl_random_pseudo_bytes($bytes));
$stm_reg3 = $conn->prepare('SELECT secondary_id FROM users WHERE secondary_id = :secondary_id LIMIT 1');
$stm_reg3->bindParam(":secondary_id", $secondary_id, PDO::PARAM_STR);
while ($stm_reg3->execute() && $stm_reg3->fetch()) {
    $secondary_id = bin2hex(openssl_random_pseudo_bytes($bytes));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多