random results from a database?

A

Anonymous

Guest
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
 
The only way I could think of doing this is a loop to generate which items to select. ie.

Code:
//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.
 
Code:
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.
 
thanks Joel. I'll try this - hopefully it'll work :D

Andrew
 
Back
Top