创建一个唯一的 8 位数字并将其无重复地插入数据库

Creating a unique 8 digit number and inserting it into a database without duplicates

我正在尝试为我网站中的每个页面创建唯一的 URL 编号,以便轻松地将其包含到站点地图中。我的网址如下所示:site.com/book/11111111site.com/book/11111112

我想为每个 ID 插入一个唯一的 URL,但遇到了一个小问题。我使用下面的代码,它并不能保证我的 thing_url 每次都是唯一的。我可以用 if-else 语句检查它的唯一性,但即使我第二次检查它,我的字符串也可能是也可能不是第二次唯一的。我不想有很多变量和 if-else 语句使用 $thing_url$thing_url2$thing_url3

有没有办法使用一个循环来检查唯一性,直到成功?这就是我现在所做的。

$thing_name = $_POST['thing_name']; // form value
$thing_url = mt_rand(10000000, 99999999); // generates 8 digit numeric string

$query = "SELECT thing_url FROM thing WHERE thing_url = '$thing_url'";
$result = $sqli->query($query);
$row = $result->fetch_assoc();
$finish = $row['thing_url'];

if($finish == $thing_url) {
    echo "Bad luck";
} else {
 $thing = $sqli->prepare("INSERT INTO thing(thing_url, thing_name ) VALUES (?,?)"); // prepare
    $thing->bind_param("ss", $thing_url, $thing_name); // bind
    $thing->execute(); // execute
    $thing->close(); // close
}

由于此类同步问题,客户端永远不应尝试生成任何唯一的内容(GUID 除外)。相反,中央协调员应该承担该责任。

在您的情况下,理想的协调器是您的数据库,MySQL。您可以使用 URL(来自 thing_url)的主键作为唯一标识符。只要数据库遵循将主键递增 1 的典型模式并且您从一个较低的数字(通常是 1)开始,这就可以正常工作。

I already use auto_incremented ID for each record and they're unique, but I want to use these thing_url's as a unique URL. auto_increment ID values are easy to guess and I don't want my site content to be crawled that easy

然后以某种 bijective 方式置换 ID,例如与一些位模式异或,旋转位,交换字节等