0

I currently use EZSQL class in php to query the MySQL database. I am trying to grab random records from the database, but I would like to know if I could randomize the results via php instead of the sql query itself. The query currently looks like this:

$results = $db->get_results("SELECT * FROM table ORDER BY RAND()");

foreach($results AS $result)
{

//code here

}

Instead could I just grab the results from the db then randomize it via php? If so, how can I do this?

3
  • 2
    shuffle Commented Feb 9, 2013 at 23:15
  • Why would you want to do this? The randomization is probably faster in the database. Commented Feb 9, 2013 at 23:21
  • If there will be a LIMIT involved, you will go back to SQL's RAND(), which works just fine. If you think RAND() is a problem for large databases (not true) then you will have to use a LIMIT to not select billions of rows. So there you have it: ORDER BY RAND() is your only choice. Commented Feb 10, 2013 at 0:15

2 Answers 2

1

ORDER BY RAND() is not recommended: Why don't use mysql ORDER BY RAND()?

Also: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

You can just call shuffle($results) to randomize an array

Sign up to request clarification or add additional context in comments.

Comments

0

Agree with @shuffle, but if you really want to use PHP I wouldn't use foreach; Instead, take $results size, get random number between 0 and length-1, and use it get n-th element from array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.