PHP MySQL生成唯一随机数


PHP MySQL generating unique random number

我不明白为什么我的代码不工作。连接工作和其他一切,然而,当我试图生成一个唯一的随机数,并从MySQL检查,如果数字是存在的,它仍然打印出一个随机数,但它不是唯一的。有人能帮我吗?下面是我的代码:

$num = rand(1,5);
$sel_query  = "SELECT *  FROM  test"; 
$result2 =  $con->query($sel_query);
$i = 1;
for (;$i<2; $i++)
{
    while($row = mysqli_fetch_array($result2))
    {
        if ($row['id'] == $num) 
        {
             $num = rand(1,5);
             $i = 0; 
        }
    }
}   

应该可以:

$is_unique = false;
$num = false;
while (!$is_unique){
    $num = rand(1,5);
    $sel_query  = "SELECT id from test where id = " . $num; 
    $result2 =  $con->query($sel_query) or die($conn->error);
    if (!mysqli_fetch_array($result2)){
        $is_unique = true;
    }
}
echo "Unique number is " . $num;   

但是如果没有其他可能的唯一数字,它将永远循环。

我知道这有点老了,但我在需要类似的答案后发现了这个问题。我已经接受了Jodes的答案并稍微更新了一下,这样它就不会永远运行,它是一个返回数字的函数,并接受一个mysqli连接作为$mysqli:

function getUniqueNumber($mysqli)
{
    $is_unique = false;
    $num = false;
    $times_run = 0;
    while (!$is_unique)
    {
        if($times_run > 10)
        {
            echo "Run too many times, dying.";
            die();
        }
        $num = rand(1,5);
        $sel_query  = "SELECT id from test where id = " . $num; 
        $result2 =  $mysqli->query($sel_query) or die($mysqli->error);
        if (!mysqli_fetch_array($result2))
        {
            $is_unique = true;
        }
        $times_run++;
    }
    return $num;
}