How do I not repeat RAND () results in php?

1

I need to create a simulation that will do a SELECT of 5 questions at random.

I'm using ORDER BY RAND() , but the results repeat, and I do not know how I can fix it.

I even created a vector that stores the code for each question, but I do not know how to compare it at the time of SELECT .

Does anyone know how I can fix this problem?

The code:

$con = conectar();
$x=1;
for($i=$x; $i<=$x+4; $i++){
 $sql = "SELECT * FROM simulado where cod_disc like 1 order by RAND()";
 $res = mysqlexecuta($con,$sql);
 $row = mysql_fetch_array($res);
 echo $i . ") " . $row['enunciado'];                                 
 $questoes[$i] = $row ['cod_questao'];
}

* The mysqlexecuta method just runs the query and checks for any runtime errors.

    
asked by anonymous 25.10.2018 / 06:16

1 answer

3

The ORDER BY RAND() by itself does not repeat any data. It just varies the order of the output.

Apparently the solution to your case is to take the query from the loop, because the problem is that you make multiple SELECT each SELECT you are redo% unnecessarily (and at each moment, the sequence changes, which causes repetition).

With a RAND , only multiple records come without repeating, just repeat the SELECT to get the next one.

It would be something like this:

$con = conectar();
$x=1;
$sql = "SELECT * FROM simulado where cod_disc like 1 order by RAND()";
$res = mysqlexecuta($con,$sql);

for($i=$x; $i<=$x+4; $i++){
 $row = mysql_fetch_array($res);
 echo $i . ") " . $row['enunciado'];                                 
 $questoes[$i] = $row ['cod_questao'];
}

I noticed that your loop is a bit complex, what is mysql_fetch_array for? It looks like some pagination, if that's what you need to review the strategy for not repeating between pages. It would be best to use $x in this case (and a seed value of LIMIT ):

$con = conectar();
$seed = mt_rand(); // Bole um jeito de sortear no primeiro acesso, mas
                   // manter o valor nas páginas seguintes pra não repetir
$pagina = 1;
$itens = 4;
$i = ($pagina - 1) * $itens + 1;

$sql = "SELECT * FROM simulado where cod_disc like 1 order by RAND($seed) LIMIT $i, $itens";

$res = mysqlexecuta($con,$sql);
while($row = mysql_fetch_array($res)) {
    echo $i . ") " . $row['enunciado'];                                 
    $questoes[$i] = $row ['cod_questao'];
    $i++;
}
    
25.10.2018 / 13:39