我有这个脚本来生成一个随机数,但我需要它是唯一的。我尝试使用while
循环来检查它是否已经存在于数据库中,但它对我不起作用。
$numbers = range(6, 1);
$random = '';
shuffle($numbers);
foreach ($numbers as $number) {
$random.= $number;
}
这是我尝试使用的代码
var stop_cycle = 0;
while (!stop_cycle) {
$numbers = range(6, 1);
$random = '';
shuffle($numbers);
foreach ($numbers as $number) {
$random.= $number;
}
$db->query("SELECT upload_ID FROM uploads WHERE upload_ID = ".$random);
// check if query returns any result
if(mysql_affected_rows() == 0) {
// DOING STUFF
// end cycle
stop_cycle=1;
}
}
答案 0 :(得分:0)
你几乎拥有它。问题是除非页面已刷新,否则您无法生成新号码。我创建了一个函数,脚本可以继续调用,直到找到没有结果的数据库条目。
<?php
function generateNumber(){
$numbers = range(6, 1);
$random = '';
shuffle($numbers);
foreach ($numbers as $number) {
$random.= $number;
}
return $random;
}
// start the do loop. If the query returns more than 0 results, it will
// pick up another number and attempt again.
do {
$number = generateNumber();
$mysqli->query("SELECT upload_ID FROM uploads WHERE upload_ID = $number");
}while(mysqli_num_rows > 0);
?>