2

i am trying to fetch random records from mysql database , which it worked but i need the records to be also unique when i fetch them as they duplicated on the output, here is my code:

    <?

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>';
}


?>

how can i do that ?

1
  • Write your sql query outside the for loop Commented May 9, 2012 at 14:44

1 Answer 1

2

You have all the code in a for loop including the code that runs the query; you "extract" 5 rows from db but only fetch the first, and repeat this 5 times. Instead you should run the query once, then loop on your results until you reach the end of the 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>';
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks :) , i just figure out that before 10 seconds :) , thank you for your time .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.