11

I have a problem selecting 6 random friends

This is the query I've got so far:

$result = num_rows("SELECT * FROM friends WHERE member_id = '".$_SESSION['userid']."'");
if($result >= 6) {
    $f_num = 6;
} else {
    $f_num = $result;
}
for($i = 1; $i <= $f_num; $i++) {
    $q_get_member_friends = mysql_query("SELECT * FROM friends WHERE member_id = '".$_SESSION['userid']."' ORDER BY rand() LIMIT 1");
    $r_get_member_friends = mysql_fetch_array($q_get_member_friends);
    echo $r_get_member_friends['friend_with'];
}

I want to select 6 random friends if the logged in user has more or equal to 6 friends

Stuck on this for a while now :/

Thanks for any help :)

4
  • 1
    Only if the person has 6 or more friends? Commented Jul 27, 2010 at 1:04
  • A bit off topic but you can save time by using braces in strings. Like instead of '".$_SESSION['userid']."'" You can use ` '{$_SESSION['userid']}'"` Commented Jul 27, 2010 at 1:12
  • only if the person has 6 or more, yes good to know :) Commented Jul 27, 2010 at 1:16
  • @Shubham If it's only a one-dimensional array, it's even enough to write "'$_SESSION[userid]'". :) Commented Jul 27, 2010 at 1:55

6 Answers 6

25

If you use:

  SELECT * 
    FROM friends 
   WHERE member_id = '".$_SESSION['userid']."' 
ORDER BY rand() 
   LIMIT 6

If the person only has 3 friends, the query will only show those three - it doesn't mean that the query will always return six rows.

Sign up to request clarification or add additional context in comments.

2 Comments

Order by rand is dangerously slow with lots of data.
There's an article here with details and alternatives: titov.net/2005/09/21/…
5

The best way I've found to select any number of random records is with OFFSET in the query.

Let's say you want 6 random records, so I'll borrow from an answer above and count the total number of friends in the database.

$sql = mysql_query("SELECT COUNT(*) AS total FROM friends WHERE member_id='". $_SESSION['userid'] ."'");

$get_count = mysql_fetch_array($sql); // Fetch the results

$numfriends = $get_count['total']; // We've gotten the total number

Now we'll get the 6 random records out of the total above (hopefully it's > 6),

$query = mysql_query("SELECT * FROM friends WHERE member_id='". $_SESSION['userid'] ."' LIMIT 6 OFFSET " . (rand(0, $numFriends));


while ($rows = mysql_fetch_array($query))
{
  /// show your $rows here
}

Using OFFSET may not be the best or most efficient, but it's worked for me on large databases without bogging them down.

1 Comment

It may not have any record after some rows if you use offset as random. I think thats better to get the results as array and then we can use shuffle method to mix the elements of the array. In order to get first 6 elements, we can use array_slice($array, 0, 6);
1

Never mind, I figured it out :)
Had to use while not for :'D

Comments

0

First select the number of friends that the user has:

"SELECT COUNT(*) as numFriends FROM friends WHERE member_id='".$_SESSION['userid']."'

...put that into a variable, let's call it "$numFriends" Then:

for($z=0;$z<6;$z++)
{
   $randomFriendIndex = rand(1,$numFriends);
   //Get the friend at that index
}

1 Comment

do I have to use that query in a num_rows or fetch_array?
0

change limit 1 to limit 6 on the eighth line.

Comments

0

Instead of SELECT * at the beginning, try SELECT COUNT(*) and use the actual return value instead of num_rows().

Your loop could generate duplicates. I would suggest trying OMG Ponies answer.

There is a whole chapter about random selection in the book SQL Antipatterns.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.