如何在PHP中生成唯一的随机数 [英] How generate UNIQUE random number in php

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

问题描述

可能重复:
用于生成随机数的算法

Possible Duplicate:
Algorithm for generating a random number

我需要为数据库中的某些条目分配一个随机生成的数字,并且该数字必须唯一. 我使用:

Hi i need to assign a randomly generated number to some entries into the database and it must be unique. I use:

$random_number = mt_rand();
mysqli_query($db_connection, "INSERT INTO my_table (rand_num, blabla) VALUES ('$random_number', '$blabla')");

但是,2个随机数相同的机会总是很少. 然后我可以做类似的事情:

But ofc there could always be a slightly low chance that 2 random numbers will be the same. Then i could do something like:

function random_check($random_number) {
    require_once('db_access.php');
    $random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
    mysqli_close($db_connection);
    $result = 1;
    while($row = mysqli_fetch_array($random_check)){
            if ($row['rand_num'] == $random_number) {
             $result=0
           }
    }
        return $result;
};

$random_number = mt_rand();
$random_check = random_check($random_number);
if ($random_check == 0) {
      $random_number = mt_rand();
}

但这只会检查一次该号码,并且仍然有可能新生成的号码已经存在于数据库中.

But this would only check the number once and there will still be a chance that the new generated number already exists into the db.

有什么建议吗? 谢谢

推荐答案

以下是您可以使用的方法:

Here is a method which you can use:

<?php
$num= mt_rand();
$con = mysql_connect("localhost","uname","password");
mysql_select_db("dbname",$con);
$sel_query  = "SELECT *  FROM  my_table WHERE rand_num =%d"; // query to select value 
$ins_query = "INSERT INTO my_table(rand_num) VALUES(%d)";    // query to insert value
$result =  mysql_query(sprintf($sel_query,$num),$con);
while( mysql_num_rows($result) != 0 ) {                      // loops till an unique value is found 
    $num = mt_rand();
    $result = mysql_query(sprintf($sel_query,$num),$con);
}
mysql_query(sprintf($ins_query,$num),$con); // inserts value 

?>

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

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