Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL select random rows

Tags:

php

mysql

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 :)

like image 864
Endre Hovde Avatar asked Jul 27 '10 01:07

Endre Hovde


1 Answers

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.

like image 159
OMG Ponies Avatar answered Sep 29 '22 06:09

OMG Ponies