PHP MySQL生成唯一的随机数 [英] PHP MySQL generating unique random number

查看:221
本文介绍了PHP MySQL生成唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我的代码无法正常工作.该连接正常工作,但是当我尝试生成一个唯一的随机数并从MySQL检查该数字是否存在时,它仍然会打印出一个随机数,但不是唯一的.有人可以帮我吗? 这是我的代码:

I don't understand why my code isn't working. The connection works and everything else however when I try to generate a unique random number and check from the MySQL if the number is there it still prints out a random number but it's not UNIQUE. Could anyone help me thx? Here's my code:

$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;   

但是,如果没有更多可能的唯一数字,它将永远循环.

But if there aren't any more possible unique numbers, it will loop forever.

这篇关于PHP MySQL生成唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆