我正在努力创建一个论坛(只是为了测试),我已经达到同步线程列表和内部帖子的地步。我依靠 mysql 中的 AUTO INCREMENT
来同步它们,但我知道它将来不会有用。
我现在的问题是,我如何生成随机数堆叠,就像 mysql auto_increment
一样?
查看线程列表,当前是
$sql = "SELECT * FROM threads WHERE th_unique='$section';
$result = mysqli_query($db,$sql);
然后我只获取数据并输出列表中的线程。
基本上,当发送插入查询时,我如何生成一个数字,就像自动递增一样?
我知道 rand()
但我最终没有发现它有效,因为它可能会重叠并使用已经存在的相同数字。
最佳答案
实际上,你可以使用AUTO_INCREMENT with replication在特定条件下。
Statement-based replication of AUTO_INCREMENT, LAST_INSERT_ID(), and TIMESTAMP values is done correctly, subject to the following exceptions:
When using statement-based replication prior to MySQL 5.7.1, AUTO_INCREMENT columns in tables on the slave must match the same columns on the master; that is, AUTO_INCREMENT columns must be replicated to AUTO_INCREMENT columns. ...
这样的例子还在继续。如果您的情况是 AUTO_INCREMENT 不起作用的情况之一 UUID是一个选项。
另请查看此答案:https://stackoverflow.com/a/37605582/267540它适用于 python/django 这是翻译成 PHP 时的样子
define('START_TIME',1470825057000);
function make_id() {
/**
* inspired by http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram
* Generates a unique identifier that isn't too complex and has a sequential nature (sort of)
*/
$t = microtime(True)*1000 - START_TIME;
$rnd = random_int(0,8388607);
return ($t << 23) | $rnd;
}
function reverse_id($id) {
$id = ($id >> 23) + START_TIME;
return $id;
}
for ($counter=0; $counter<100; $counter++) {
$id = make_id() ;
$time = reverse_id($id);
print "$id $time \n";
}
print 'Ending time ' . microtime(True)*1000;
如您所见,数字看起来是连续的,但它们仍然可以安全复制。
关于php - 为mysql生成数字顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38869541/