Randomize SQL query results
There are many ways to get random database results, here I explain two of them.
/* ** The first way: ** ** Let your database server randomize the database rows for you. ** This works by adding "ORDER BY RAND()" to your query string. ** (in MSSQL you have to use "ORDER BY NEWID()") */ /* ** The second way: ** ** If you want to use the "ORDER BY" for another field, you ** can randomize the resulting array by using the shuffle function: */ // Connect to database: $Link = mysql_connect('localhost','test_user','test_password') or die('Could not connect to the server!'); // Select a database: mysql_select_db('test_db') or die('Could not select a database.'); // SQL-Query (select last 10 entries): $SQL = "SELECT * FROM todo_list ORDER BY id DESC LIMIT 0,10"; // Execute the query: $Result = mysql_query($SQL) or die('A error occured: ' . mysql_error()); // Create empty array for the fetched rows $Rows = array(); // Fetch all rows and store them in the new array: while ($Row = mysql_fetch_assoc($Result)) $Rows[] = $Row; // Randomize all result rows shuffle($Rows); // Now do something cool with the randomized // results: foreach($Rows as $Data){ // ... print $Data['Name']; print "<br/>\n"; } // Please read the whole snippet before // you recommend --> ORDER BY RAND()
Snippet Details
-
AuthorJonas John
-
LicensePublic Domain
-
LanguagePHP
-
Created09/18/2007
-
Updated02/11/2008
-
Tagsdatabase functions, random
Sorry folks, comments have been deactivated for now due to the large amount of spam.
Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!
Older comments:
cssfreakie March 10, 2011 at 06:57
@alexander
inmagine what would happen if you have table with a million rows and you only needed 20 rows at random. That would be pretty much work at database level
inmagine what would happen if you have table with a million rows and you only needed 20 rows at random. That would be pretty much work at database level
Alexander R September 23, 2008 at 19:36
Hey, great article, i saw at the end that you added please read the whole snippet before recommending RAND(), so how come you decided to implement the randomization part at the php level ?