简体   繁体   中英

PHP random choice of results with a limit

I have a collection of files (each file containing a grammar exercise), and a table in my DB where each file is described according to its topic, tense and type.

I have a form where I can select the topic, tense and type I need. 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 but 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.

Do you have any ideas about how to shuffle all the candidate files and then output n of them, where n=$limit?

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.";
}
?>

I would use MySQL's RAND() function:

SELECT column FROM table
ORDER BY RAND()
LIMIT $limit 

or some such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM