Jump to content

Randomizing query results


ViperSBT

Recommended Posts

Using the following code:
[code]$sql = "SELECT m.id, m.name, m.picture, AVG(s.score) as average FROM models m LEFT JOIN scoring s ON s.id = m.id WHERE m.category = '$game' GROUP BY m.id ORDER BY average DESC";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$row = mysql_fetch_array($result);

$contestants = array_rand($row, 10);[/code]
I am getting an error:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array...[/quote]
I guess what I am trying to do may be a little different than what array_rand() is for. I rant to take 10 random rows and put them in the new array. The array $row has 30 rows of elements, and I want to take 10 on those.
Link to comment
https://forums.phpfreaks.com/topic/11547-randomizing-query-results/
Share on other sites

When you do an mysql_fetch_array() or mysql_fetch_assoc() you are getting one row returned from the set of rows matching your query. In order to fetch all of them you need to put the function in a "while" loop:
[code]<?php
$sql = "SELECT m.id, m.name, m.picture, AVG(s.score) as average FROM models m LEFT JOIN scoring s ON s.id = m.id WHERE m.category = '$game' GROUP BY m.id ORDER BY average DESC";
$result = mysql_query($sql) or die("Problem with the query: $sql<br>" . mysql_error());
$count = mysql_num_rows($result);
$tmp = array();
while ($row = mysql_fetch_array($result))
     $tmp[] = $row;
$contestants = array_rand($tmp, 10);
?>[/code]

Ken
You can also get a randomly ordered result from MySQL.

Refer to this topic:
[a href=\"http://www.phpfreaks.com/forums/index.php?showtopic=94498\" target=\"_blank\"]http://www.phpfreaks.com/forums/index.php?showtopic=94498[/a]

Edit: What is the point of using ORDER BY average if you are going to randomize them?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.