Hello! I have set up a script form called " form tools " without a problem, This script gathers all information in the registration form and stores it into a database (php and mysql), Now I would like to randomly choose 5 people from the data I collected from the database randomly, Since it’s a game, I would like it to be as random as possible, how do I do this?

If you have a counter or id field in your table which is unique, you can do this easily.

<?php
$connection=mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
$query="select * from tablename";
$result=mysql_query($query);
$max=mysql_num_rows($result);//count the total records in the table
$random_members=array();
while(count($random_members) <= 5){ // until 5 members are selected
	$random=rand(1,$max);//generate random number
	if(! in_array($random,$random_members)){ //if random number is not in the array, add it. 
	 	$random_members[]=$random;
 	}
}
print_r($random_members); //print random numbers
?>

Thats it.. Cheers.. :)

If you have a counter or id field in your table which is unique, you can do this easily.

<?php
...... 
$query="select * from tablename";
$result=mysql_query($query);
..........
?>

There's a query that does this for you .. :)

select * from tablename order by rand() limit 5

There's a query that does this for you .. :)

select * from tablename order by rand() limit 5

I didn't know that ! thanks :)

This article has been dead for over six months. Start a new discussion instead.