John
John

Reputation: 10146

Randomizing database results using php instead of mysql query

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?

Upvotes: 0

Views: 854

Answers (2)

FoolishSeth
FoolishSeth

Reputation: 4031

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

Upvotes: 1

mladen.plavsic
mladen.plavsic

Reputation: 189

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

Upvotes: 0

Related Questions