Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top