random results from a database?

Codes here !

Moderators: macek, egami, gesf

User avatar
bezmond
Moderator
Moderator
Posts: 312
Joined: Sat Apr 05, 2003 4:33 am
Location: Mansfield, UK
Contact:

random results from a database?

Postby bezmond » Sun Jun 29, 2003 4:18 am

Hey,
can I select 20 RANDOM results from a database of 25 records without getting repeatition?
I currently use rand(), but that doesn't work half the time - when it repeats a number, it screws up :|

Regards,
Andrew Berry

Joel
New php-forum User
New php-forum User
Posts: 193
Joined: Sat Mar 29, 2003 11:57 pm
Location: Auckland, New Zealand
Contact:

Postby Joel » Mon Jun 30, 2003 9:07 pm

The only way I could think of doing this is a loop to generate which items to select. ie.

Code: Select all

//Connect to database
$x = 1;
echo "<pre>";
do {
   $id = rand(1, 5);
   while (isset($idlist["$id"])) {
      $id = rand(1,5);
   }
   $idlist["$id"] = $id;
   if (@$where == "") {
      $where = "id=$id";
   }
   else {
      $where .= " or id=$id";
   }
   ++$x;
} while ($x<=5);
echo "Where statement is: " . $where . "\n\r";

$sql = mysql_query("SELECT `field`, `id` FROM table WHERE $where LIMIT 20");

while ($myrow = mysql_fetch_array($sql)) {
   print_r($myrow);
}
echo "</pre>";



Took me a bit of thinking for that. Should work for you. I just used the print_r and the whole pre deal to show the results.

I should really write it into a function.

Joel
New php-forum User
New php-forum User
Posts: 193
Joined: Sat Mar 29, 2003 11:57 pm
Location: Auckland, New Zealand
Contact:

Postby Joel » Tue Jul 01, 2003 7:06 am

Code: Select all

function NoRepRand($min, $max, $quantity) {
   $i = 1;
   do {
      $rand = rand($min, $max);
      while (isset($idlist["$rand"])) {
         $id = rand($min,$max);
      }
      $list[] = array("value"=>$rand);
      ++$i;
   } while ($i<=$quantity);
   return $list;
}


Theres my function for a no repeat random number array.

User avatar
bezmond
Moderator
Moderator
Posts: 312
Joined: Sat Apr 05, 2003 4:33 am
Location: Mansfield, UK
Contact:

Postby bezmond » Tue Jul 01, 2003 1:34 pm

thanks Joel. I'll try this - hopefully it'll work :D

Andrew


Return to “mySQL & php coding”

Who is online

Users browsing this forum: Bing [Bot] and 1 guest