List table values randomly with RAND() or ARRAY for a Captcha

Asked

Viewed 34 times

-1

I’m creating a CAPTCHA and for that I made a table with alternatives that the user will have to select the IMAGE correct.

First I draw a word.

Example: You must select the word FAN

And then I put four words from the bank into ORDER random, but sometimes the word can come FAN how not.

Is there any way to USE RAND, but requiring it to show 1 specific value?

Keep going like I’m trying to do:

<?php   $querye = $pdo->prepare("SELECT id, palavra, imagem FROM captcha WHERE id IN ('$linhas->id') OR rand(id) ORDER BY rand('$linhas->id') LIMIT 4");

for ($i=0; $i < count($palavras); $i++) { 

$valor_opcao = $palavras[$i]['id']; ?>



 <label for="palavra<?php echo $valor_opcao; ?>">



<input type="radio" name="palavraid" autocomplete="off" id="palavra<?php echo $valor_opcao; ?>" value="<?php echo $valor_opcao; ?>">

                                  

<img src="<?php echo $palavras[$i]['imagem']; ?>" id="img">
                   </label>
                          
<?php
    }


?>

They tell me you can use it ARRAY with shuffle, but I have no idea how to do.

  • pq does not select the correct image and +3 (or as many as you like) random, and merges it into a query using union?

  • because the order needs to be random example:

  • A, B, C, D ------ B C D A ------------ C A B D

  • can user an order by Rand to resolve this :)

  • just that I want to use a LIMIT, example, put to show only 4 words in random order, and sometimes it shows the selected word and sometimes not

  • I put in an answer, it is easier to explain, see the example working

Show 1 more comment

1 answer

2


Basically you need two darlings:

  • one with the desired word;
  • other without the desired plavra limits to 3 (or more)

Then just sort the result randomly:

(SELECT id, palavra FROM captcha WHERE id IN (3))
UNION
(SELECT id, palavra FROM captcha WHERE id NOT IN (3)  ORDER BY RAND() LIMIT 3)
ORDER BY RAND();

Might have working here (id 3 is the word that should always come) : https://www.db-fiddle.com/

In what, the secret is to separate the queries in parentheses, because in the second query, you want to limit to 3 results, to have all 4, and only apply the order at the end of the UNION of the two darlings :)

  • DEUUUU right thank you very much

Browser other questions tagged

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