Randomize SQL query results
There are many ways to get random database results, here I explain two of them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
** 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){
// ...
X
Url: http://www.jonasjohn.de/snippets/php/randomize-sql-query-results.htm
Language: PHP | User: ShareMySnippets | Created: Oct 16, 2013