Tuesday, 23 January 2018

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()

0 comments:

Post a Comment