PHP MySQL selects random strings

I have a problem with 6 random friends

This is the query that I still have:

$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 registered user has more than or equal to 6 friends

Stuck on this for a while: /

Thanks for any help :)

+6
php mysql
source share
6 answers

If you use:

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

If a person has only 3 friends, the query will show only three: this does not mean that the query will always return six rows.

+15
source share

The best way to find any number of random entries is by using OFFSET in the query.

Say you want 6 random entries, so I’ll get the answer above and calculate 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 get 6 random entries from the total above (hopefully this is> 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 effective, but it worked for me in large databases without linking them.

+5
source share

Nothing, I get it :)
Use , not for : 'D

+1
source share

First, select the number of friends the user has:

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

... put this in a variable, name it "$ numFriends" Then:

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

change limit 1 to limit 6 on the eighth line.

0
source share

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

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

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

0
source share

All Articles