Imad Arifi
Imad Arifi

Reputation: 3

RAND returns suplicates and sometimes no values

I'm trying to make a quiz using mysql and php I want to fetch questions randomly from the database I have a truble with rand function sometimes it seturns no value and returns also duplications I tried to find a solution on the net but couldn't make it this is the part of code that generate the problem

$link=mysqli_connect("localhost","root","","database"); 
$req="SELECT DISTINCT *
FROM `qst_s`
WHERE `id_qst` = ROUND( RAND()*49 ) + 1 AND `level` = '1'  LIMIT 40";
$result=mysqli_query($link,$req);
$question=$result->fetch_assoc();

I have 50 questions in my database level 1 by the way

Upvotes: 0

Views: 61

Answers (1)

AgeDeO
AgeDeO

Reputation: 3157

The simplest way of selecting random rows from the MySQL database is to use "ORDER BY RAND()" clause in the query.

SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

The problem with this method is that it is very slow. The reason for it being so slow is that MySQL creates a temporary table with all the result rows and assigns each one of them a random sorting index. The results are then sorted and returned.

Your query would look like this:

$req="SELECT DISTINCT *
FROM `qst_s`
WHERE `level` = '1'
ORDER BY RAND()
LIMIT 40";

Upvotes: 1

Related Questions