Results coming from the database repeated

0

I'm creating a quiz , but how do I stop the questions from recurring?

// Executa uma consulta que pega as questoes
$sql = 'SELECT * FROM 'questoess' WHERE IdPergunta=' .rand(1,4);
$query = $mysqli->query($sql);

    while ($dados = $query->fetch_array()) {
        echo ' ' . $dados['Pergunta'] . '<br><br>';
        echo '<input type="radio" name="a" />'. 'AlternativaA: ' . $dados['AlternativaA'] . '<br>';
        echo '<input type="radio" name="b" />'. 'AlternativaB: ' . $dados['AlternativaB'] . '<br>';
        echo '<input type="radio" name="c" />'. 'AlternativaC: ' . $dados['AlternativaC'] . '<br>';
        echo '<input type="radio" name="d" />'. 'AlternativaD: ' . $dados['AlternativaD'] . '<br>';
        echo '<input type="radio" name="e" />'. 'AlternativaE: ' . $dados['AlternativaE'] . '<br>';
}
    
asked by anonymous 21.09.2017 / 04:56

1 answer

3

The way you're doing, with rand(1,4) by php:

$sql = 'SELECT * FROM 'questoess' WHERE IdPergunta=' .rand(1,4);

You will have to make multiple queries to the database and would have to store the ids that had already gone out not to repeat them, complicating the algorithm drastically.

It is much simpler to randomize the query and extract the amount of results you want, using rand() and LIMIT :

$sql = 'SELECT * FROM 'questoess' order by rand() LIMIT 5';

In this last example, you directly get 5 database questions, randomly, subtracting only using them.

Note: Confirm that the table name is correct ( questoess ) because in terms of spelling it has s more

    
21.09.2017 / 11:26