Using PHP's shuffle() instead of MySQL's rand()

I currently have a block of code that talks to a certain table in the MySQL database and displays according to both the area and serv columns. I was reading of a method to use ORDER BY RAND() in my MySQL query (which works for me) but I heard that slows down the server and I should randomize my results with PHP instead with shuffle(). How would I modify my code to randomize them properly?

$profiles = "SELECT * FROM profile WHERE area='".$areaid."' AND serv='".$servid."' AND active='1'"; $numresults=mysql_query($profiles); $numrows=mysql_num_rows($numresults);

// rows to return

if ($numrows == 0)
  echo "<p></p>";

// next determine if s has been passed to script, if not use 0
  if (empty($s)) {

// get results
  $profiles .= " limit $s,$limit";

  $result = mysql_query($profiles) or die("Couldn't execute query");

echo "";
$count = 1 + $s ;

// now you can display the results returned
  while ($row = mysql_fetch_array($result)) {
  $instname = $row["inst_name"];
  $profileid = $row["profile"];
  $logo1 = $row["logo1"];
  $city = $row["city"];
  $state_abbr = $row["state_abbr"];
  $zip = $row["zip"];
  $bio = $row["bio"];
  $price = $row["rel_fee"];
  $years = $row["years"];
  $level = $row["level"];
  $honors = $row["honors"];
  $tagline = $row["tagline"];

  echo "<div class=\\"miniprofile\\">
  <div class=\\"miniprofile_logo\\">Profile<br><a href=\\"/profile/$profileid\\"><img src=\\"$domain/images/profiles/$logo1\\" alt=\\"\\"></a>
  <div class=\\"miniprofile_head\\"><a href=\\"/profile/$profileid\\" style=\\"font-size:18px;\\">$instname</a>
  <br>$city, $state_abbr $zip
  <br><br><strong>Service:</strong> $servname
  <br><strong>Experience:</strong> $years yrs &nbsp;&nbsp;&nbsp;<strong>Price:</strong> $price
  <br><strong>Honors:</strong> $honors
  </div><br><br>" ;

  $count++ ;

$currPage = (($s/$limit) + 1);

//break before paging
  echo "<br>";

Ordering with MySQL is faster than with PHP, and the extra PHP code required would be an extra bloat.

MySQL is very efficient, so do the heavier things in that. After all, it’s a server devoted to data handling!

ORDER BY Rand() is quite inefficient

are your PK values evenly distributed? for example, auto_increment numbers usually are, even if there have been a modest number of deletions

(if there is a large gap, the following method won’t work too well)

use MIN(pk) and MAX(pk) to determine the current range of numbers, then use php to generate a random id number in between these two, and select the first row with pk >= this random value…

lots more efficient, even with 2 queries against the database

r937 is right.

If you do RAND() in mysql, it can get a bit slow.
If you do shuffle() in php is just stupid, since your have to transfer all your data, then order it.