Repeated results from the database

Asked

Viewed 33 times

0

I’m creating a quiz, but how do I make sure the questions don’t repeat themselves?

// 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>';
}
  • Welcome, you can start by doing tour and to get answers that solve your question / problem read How to ask a good question?.

  • 1

    Is the idea to show all questions in random order? Is this code you put running inside a loop? For it seems to me that he selects only one question at a time and there would be no repetition.

  • puts the question printing before the while, taking only the content of the first line, and then at the while you print the alternatives. It is repeating because in each row you have the alternative and the question... the question getting inside the while, will be printed as well

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 left to not repeat them, drastically complicating the algorithm.

Much simpler will be to sort randomly in 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 get directly 5 database questions, randomly, leaving only use them.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.