PHP当变量不满足要求时重复一个函数

时间:2014-08-20 10:01:01

标签: php mysql loops repeat

我是PHP的新手(我正在学习它)所以有人可以帮助我修复我的脚本吗?

$total = mysql_num_rows(mysql_query("SELECT * FROM files;"));
$rand = rand(0,$total);
$check = mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";"));
do {
$rand;
}
while($check < 1);

我编写此代码以从MySQL获取随机列ID(我尝试了“ORDER BY RAND()”,但它太慢了),当MySQL的表中不存在此ID时,它将重复此作业,直到找到存在的ID用这种方式:

$check = mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";"));

但我认为编码时错了。请帮我解决。感谢。

2 个答案:

答案 0 :(得分:4)

您需要将查询放在循环中,否则它不会再次实际检查。见下文:

$total = mysql_num_rows(mysql_query("SELECT MAX(id) FROM files;"));
$check = 0;
do {
$rand = rand(0,$total);
$check = mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";"));
}
while($check < 1);

答案 1 :(得分:0)

可以吗?

do {
$rand = rand(0,$total);
}
while(mysql_num_rows(mysql_query("SELECT * FROM files WHERE id=".$rand.";")) < 1);