开发者

echo random id numbers from mysql database without repeating numbers?

开发者 https://www.devze.com 2023-02-24 07:37 出处:网络
How do I echo random id numbers from mysql database without repeating numbers? this is my sample code:

How do I echo random id 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 have instances like "1 1 3 2 4 5" where 1 is echoed开发者_如何学运维 twice instead of once. thanks in advance


Just order your results by rand and limit their number, your id has to be unique :

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


The Problem is, that you do a SELECT inside of the loop, instead of selecting once and loop 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 recordsets is ugly, use SELECT count(id)instead


If you're coming out of php you're probably better off (faster, easier, no locking issues) to randomize your numbers there. And SQL queries inside loops is an antipattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消