简体   繁体   中英

Select Random and unique rows from database on button click

I am trying to develop a quizz app in PHP and MySQL. Now i have a case where i have to get one random row from database on button click. And the question appeared once should not appear next time.

What i did was, i selected random row from database then stored the id on session variable as an array. And next time while fetching the data of that random row checked if the questions id lies on that array or not. If the question id is already on that array then reload the page to get new question else display the question.

The code i have used is as follows Code to select random and unique row

Code to display value and save value on array

在此处输入图片说明 在此处输入图片说明

Sorry!, I couldn't put code in here due to format problem.

Using your way, when every question on your database is shown to the user, the page will enter an infinite redirection loop. You might use a query like this:

 SELECT * FROM tbl_question 
     WHERE question_id NOT IN ([previously shown ids]) AND is_active='yes' 
     ORDER BY RAND() LIMIT 1

this way, if you don't get any result, you'd assume that all the questions have been shown to the user, and you won't need a page refresh to switch to another question when the question exists in the session variable.

In your code, modify:

 $where = "is_active='yes'"

to

 $where = "is_active='yes' AND id NOT IN (" . implode(",", $_SESSION["ques"]) . ")";

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