3

I want to select 6 random rows from my table. Here are my problems.

  1. The RAND () command doesn't seem to be that random, some rows get selected more often than others.

  2. I want the random choice to be fast even if the table gets large (10000 observations or more).

<?php
$con=mysqli_connect("mysql_host","mysql_user","mysql_password","mysql_database");


$result=mysqli_query($con, "SELECT * FROM my_table ORDER BY RAND() LIMIT 6");

$count = 0;
while($row=mysqli_fetch_row($result)){
    $postsarray["one.$count."] = $row[1];
    $postsarray["two.$count."] = $row[2];
    $count++;
}

$encodedArray = array_map(utf8_encode, $postsarray);
echo json_encode($encodedArray);


mysqli_close($con);

?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
user5095266
  • 119
  • 2
  • 7

1 Answers1

4

Use order by rand(). I's perfectly random and - for only 10k rows - it's fast.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345