I have a collection of files (each file containing a grammar exercise), and a table in my DB where each file is indexed according to its topic, tense and type.
Using a form, users can select the topic, tense and type of exercise. Using the following PHP script, I can retrieve the file(s) I searched for. The maximum number of retrieved exercises corresponds to the value of $limit.
Everything works fine, but what I can’t do is to shuffle all the retrieved exercises and return them at random. As it is, the script browses the DB top-down, retrieves the exercises and it stops when it reaches the amount of $limit. As a consequence, the exercises stored at the bottom of the table in the DB, are never retrieved.
[php]if(isset($_POST[‘limit’], $_POST[‘topic’], $_POST[‘tense’], $_POST[‘type’]))
{
$counter = 0;
$limit = intval($_POST[‘limit’]);
$result = ‘’;
foreach ($_POST[‘topic’] as $key_topic => $value_topic)
{
foreach ($_POST[‘tense’] as $key_tense => $value_tense)
{
foreach ($_POST[‘type’] as $key_type => $value_type)
{
$q_to_te_ty = “SELECT * FROM items WHERE topic = '”.$value_topic."’ AND tense = ‘".$value_tense."’ AND type = ‘".$value_type."’ ORDER BY RAND()";
$qu_to_te_ty = mysql_query($q_to_te_ty);
while ($rows = mysql_fetch_array($qu_to_te_ty) and ($counter < $limit))
{
$result = $rows[‘file’];
readfile(“files/$result”);
echo “----------------------------------------”."\n"."\n";
$counter++;
}
}
}
}
if(!$result)
{
echo “SORRY. There are no exercises in the database which match your search.”."\n".“Please try selecting different values.”;
}
}
else
{
echo “ERROR: You forgot to check something.”."\n".“Please select at least one type, topic and tense value. And don’t forget to set a number of exercises.”;
}
?>[/php]
Do you have any ideas about how to shuffle all the candidate files and then output n of them, where n=$limit?