我想在 PHP 中生成一个不重复且长度为 16 的随机数代码。最好的方法是什么?我使用这段代码:
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 14) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
但这会产生 1 个随机数。我想要 30000 个随机数。我该怎么办 ?
我也使用此代码,但这不会生成 16 长度:
<?php
$con=mysqli_connect("localhost","root","","test1");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
for ($s=0;$s<10;$s++) {
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 16) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
echo nl2br("$code <br/>");
mysqli_query($con,"INSERT INTO test (ID, Code, Type, Used)
VALUES ('', '".$code."','1', '0')");
}
for ($s=0;$s<10;$s++) {
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 16) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
echo nl2br("$code <br/>");
mysqli_query($con,"INSERT INTO test (ID, Code, Type, Used)
VALUES ('', '".$code."','2', '0')");
}
for ($s=0;$s<10;$s++) {
$possible = '0123456789';
$code = '';
$i = 0;
while ($i < 16) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
echo($code);
echo nl2br("$code <br/>");
mysqli_query($con,"INSERT INTO test (ID, Code, Type, Used)
VALUES ('', '".$code."','3', '0')");
}
mysqli_close($con);
?>