David19801
David19801

Reputation: 11448

randomize mysql output as easily as possible

I have the mysql statement:

$mysql=mysql_query("SELECT id,name FROM table1 ORDER BY id LIMIT 10");

From this I'm doing

while($row = mysql_fetch_array($mysql)){
    echo $row['name'].'<br>';
}

Now i'm trying to shuffle the rows I got out of mysql without using ORDER BY RAND() as thats causing slowdown.

Whats the correct syntax to program this in so the rows come out shuffled?

Upvotes: 1

Views: 2088

Answers (4)

Maxime Pacary
Maxime Pacary

Reputation: 23041

Using shuffle() in PHP or any PHP-side sorting method, will only randomize, at each execution, the very same 10 rows (LIMIT 10) from the MySQL table.

Although more efficient, the results will be completely different to what is achieved by ORDER BY RAND().

It's difficult to know which of the two behaviors the OP asks for, but if it's the second one (since he has tried ORDER BY RAND()), I propose to use a more efficient way for retrieving 10 rows at random from the whole MySQL table (not a subset of its rows): see Quassnoi's solution (and SO question Faster to randomize many results on MySQL Server or in PHP).

Upvotes: 0

rockerest
rockerest

Reputation: 10508

If you don't necessarily need them to

"come out shuffled"

...as in "out of the database," then you can do the shuffle immediately after you retrieve all of the records.

Since you can fetch all rows as an associative array, you can then just shuffle the result. This will give you a random order of the rows returned.

In your case:

$mysql = mysql_query("SELECT id,name FROM table1 ORDER BY id LIMIT 10");

$results = array(); //this might be unnecessary

while($row = mysql_fetch_array($mysql))
{
    array_push($results, $row);
}

shuffle($results);
foreach( $results as $row )
{
    echo $row['name'] . "<br />";
}

Upvotes: 1

netcoder
netcoder

Reputation: 67695

Use shuffle:

$results = array();
while($row = mysql_fetch_array($mysql)){
    $results[] = $row['name'];
}

shuffle($results);

Upvotes: 3

DShook
DShook

Reputation: 15664

Put the results into a php array then pick them out of the array at random.

This should work, but I haven't tested it:

while($row = mysql_fetch_array($mysql)){
    $array[] = $row['name'];
}

$c = count($array);
for($i = 0; $i < $c; $i++){
    $r = rand(0, $c - ($i + 1));
    echo $array[$r];
    unset($array[$r]);
}

Upvotes: 0

Related Questions