문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top