Jump to content

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?
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.