MikeIsMad
MikeIsMad

Reputation: 33

Having trouble spitting out mysqli random numbers

I need to populate 2x user names from a MySQL db randomly.

Say I have clinton, sanders and trump as users in my db (sorry couldn't help myself).

I want just two users randomly entered into variables. I have read too many scripts and got myself horribly confused.

  $result = mysqli_query($mdb, "SELECT user FROM `table`");
  $row = mysqli_fetch_row(array_rand($result,2));
  echo $row[0] . "\n";
  echo $row[1] . "\n";

I'm actually going to hit the sack as my teddy bear is lonely, so will review and reply to answers tomorrow morning. Thanks.

Upvotes: 0

Views: 41

Answers (1)

AceKYD
AceKYD

Reputation: 1140

I think you should leave your teddy bear alone once more and use this query directly instead

 $result = mysqli_query($mdb, "SELECT user FROM `table` ORDER BY RAND() LIMIT 0, 2");

This would automatically give you two random entries from the db and you wont need to use array_rand() anymore

With reference to the question in the comments regarding the implications on a large base, upon research it would have a big implication. I found a comment on this http://www.petefreitag.com/item/466.cfm that provides a better option

If you have a table with many rows, you can make this query much faster. A simple SELECT * FROM table ORDER BY RAND() has to do a sort in memory- expensive. If you change the query to SELECT * FROM table WHERE RAND()>0.9 ORDER BY RAND() then you've reduced the overhead of the sort by 90%. This will have the overhead of many RAND() statements, but on DB2 mainframes, it is a much faster technique.

Upvotes: 2

Related Questions