how to randomize retrieval of question from database?

后端 未结 5 1451
南旧
南旧 2021-01-20 15:06

.i have the following code:



        
5条回答
  •  隐瞒了意图╮
    2021-01-20 15:24

    Many of these answers seem to be overlooking the fact that, each time you send a request to the server, you are generating a brand randomised list of questions, and then selecting 5 of those, based on your current page.
    This means that you may get repeated questions and means that you can't go back and forth up the list, i.e. it's not pagination, it's just 5 random questions each time.

    One way to deal with this is to generate a randomized array of numbers that correspond to the key field of the question table. This is then stored in a persistent manner on the server and associated with a key that is passed back to the client (the session ID, perhaps).

    Then, when the user accesses a page, the session ID comes in; this is used to identify the randomized array; the $page_num is used as an index into the array:

       $question_ids = array_slice($randomized_array, ($page_num - 1)*5, 5);
    

    Next, you'd grab your questions using:

       $ids_for_query = array_map('mysql_real_escape_string', array_values($question_ids));
       mysql_query("SELECT * FROM questions WHERE id IN (".implode(',', $ids_for_query ).")");
    

提交回复
热议问题