如何使用唯一值生成自动编号

时间:2014-05-14 05:49:29

标签: php

大家好我有一张两个主键的表一个 ID 正在使用

来自AUTO_NUMBER的

值从10000开始并继续。

第二个字段是 ImageID ,这是主键+唯一索引意味着无法接受重复

但是对于这个我使用隐藏的HTML字段,但是我使用 rand()函数。

在这里问题是它产生重复的数字,我需要唯一的值导致图像

字段不接受重复。

我应该使用哪个函数来生成唯一的数字。

以下是隐藏的字段代码:

<input type="hidden" name="ImageID" id="ImageID" value="<?php echo rand(1000,9999999999); ?>" />

4 个答案:

答案 0 :(得分:1)

当前的unix时间戳始终是唯一的。您还可以在几微秒内获得它以获得额外的精确度。

microtime()

为了防止在完全相同的微秒(似乎不太可能)的情况下添加条目的任何可能的冲突,您可以向其附加一个随机数。

答案 1 :(得分:0)

您可以使用uniqid()。 uniqid()函数根据microtime(当前时间,以微秒为单位)生成唯一ID。或者你也使用time()。

答案 2 :(得分:0)

你也可以试试这个:

<?php
$imageId = range(1000, 10000);
shuffle($imageId);
?>

<!-- you can use loop -->
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo $imageId[0]; ?>" />
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo $imageId[1]; ?>" />
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo $imageId[2]; ?>" />
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo $imageId[3]; ?>" />

答案 3 :(得分:0)

<input type="hidden" name="ImageID" id="ImageID" value="<?php echo time(); ?>" />
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo time(); ?>" />
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo time(); ?>" />
<input type="hidden" name="ImageID" id="ImageID" value="<?php echo time(); ?>" />