Echo random id numbers from mysql database without duplicate numbers?

How to echo random number numbers from mysql database without repeating numbers?

this is my sample code:

$query = mysql_query("SELECT * FROM store"); $number=mysql_num_rows($query); for ($count=1; $count<= $number ; $count++) { $id = mysql_query ("SELECT id FROM store ORDER BY RAND() LIMIT $number"); $id = mysql_fetch_assoc($id); $id = $id['id']; echo $id; } 

It will echo six random numbers, but it has instances such as "1 1 3 2 4 5", where 1 is repeated twice, not once. thank you in advance

+4
source share
3 answers

The problem is that you are executing SELECT inside the loop, instead of having to select once and iterate over the result.

 $query = mysql_query("SELECT * FROM store"); $number=mysql_num_rows($query); $result = mysql_query ("SELECT id FROM store ORDER BY RAND() LIMIT $number"); while ($row = mysql_fetch_assoc($result)) { echo $row["id"]; } 

BTW: SELECT * to get the number of record sets ugly, use SELECT count(id) instead

+2
source

Just order your results by rand and limit their number, your identifier should be unique:

 SELECT * FROM store ORDER BY RAND() LIMIT 0,6 
+5
source

If you exit php, you are probably better (faster, easier, without blocking problems) to randomize your numbers there. And SQL queries inside loops are an antipattern.

0
source

Source: https://habr.com/ru/post/1348044/


All Articles