Jump to content


Photo

Picking a random group of records from a database


  • Please log in to reply
2 replies to this topic

#1 Federal

Federal
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 09 August 2006 - 11:37 PM

Ahoy!

I'm trying to code a tournament registration system. Long story short, a component of registration is a lottery; I've got more entrants than I do competition berths, so I need to pick 40 records at random from a MySQL database, with no duplication. I'm aware that there are other, non-PHP-based systems to do this, but I'd like to turn this into a learning experience if at all possible. :)

Speaking of possible... is it possible? What I'm currently toying with:
- Add a "selected" field to the database, default "no".
- Have it pick a random number between 1 and however many, and call up the database record attached to that number.
- If that record is already toggled as selected, toss it back and roll again. If it isn't, toggle it to "yes", and roll again until you hit 40.

Would this work? I'd be running the script on IBserver, so bandwith and server drain isn't a concern.

#2 AndyB

AndyB
  • Staff Alumni
  • Advanced Member
  • 5,465 posts
  • LocationToronto

Posted 10 August 2006 - 12:21 AM

$query = "SELECT * from your_tablename ORDER by RAND() LIMIT 40";

Legend has it that reading the manual never killed anyone.
My site

#3 corbin

corbin
  • Staff Alumni
  • Advanced Member
  • 8,129 posts

Posted 10 August 2006 - 12:32 AM

Speaking of possible... is it possible? What I'm currently toying with:
- Add a "selected" field to the database, default "no".
- Have it pick a random number between 1 and however many, and call up the database record attached to that number.
- If that record is already toggled as selected, toss it back and roll again. If it isn't, toggle it to "yes", and roll again until you hit 40.


mysql_query("ALTER TABLE `your_table` ADD `selected` INT( 1 ) NOT NULL DEFAULT '0'");
$q = "SELECT * FROM `your table`";
$n = mysql_num_rows($q);
$lotto_array = array();
while($i <= 40) {
$q = "SELECT * FROM `your_table` where `id` = mt_rand(1, $num) where `selected` = '0'";
$row = $mysql_fetch_array($q);
$lotto_array[] = $row['what_ever_field_you_want_to_save'];
mysql_query("UPDATE `your_table` SET `selected` = '1' AND `id` = '{$row['id']}'");
$i++;
}
[code=php:0]

Should work... Didnt test it though so it might not :D

Why doesn't anyone ever say hi, hey, or whad up world?




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users