2

我正在尝试random从数据库中获取记录mysql,它可以工作,但是当我获取它们时我也需要记录,unique因为它们在输出中重复,这是我的代码:

    <?

for ($counter = 1; $counter <=5;$counter++) 
{

$randomPostSelect = mysql_query("SELECT DISTINCT * FROM beventreservation WHERE (beventStatus='online' OR beventStatus='soldout') ORDER BY RAND() LIMIT 5") or die(mysql_error());

$fetchPosts = mysql_fetch_array($randomPostSelect) or die(mysql_error());


echo '<li><a href="reservation.php?rev='.$fetchPosts['eventId'].'">'.$fetchPosts['eventTitle'].'</a></li>';
echo '</br>';
}


?>

我怎样才能做到这一点 ?

4

1 回答 1

2

您在 for 循环中拥有所有代码,包括运行查询的代码;您从 db 中“提取”5 行,但只获取第一行,然后重复 5 次。相反,你应该运行一次查询,然后循环你的结果,直到你到达末尾results

<?
$randomPostSelect = mysql_query("SELECT DISTINCT * FROM beventreservation 
        WHERE (beventStatus='online' OR beventStatus='soldout') ORDER BY RAND() LIMIT 5")
    or die(mysql_error());

while ($fetchPosts = mysql_fetch_array($randomPostSelect))
{
    echo '<li><a href="reservation.php?rev='.$fetchPosts['eventId'].'">'.$fetchPosts['eventTitle']
        .'</a </li>';
    echo '</br>';
}
?>
于 2012-05-09T14:45:45.720 回答