Jump to content

Picking a random group of records from a database


Federal

Recommended Posts

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.
Link to comment
Share on other sites

[quote]
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.

[/quote]

[code=php:0]
mysql_query("ALTER TABLE `your_table` ADD `selected` INT( 1 ) NOT NULL DEFAULT '0'");
[/code]
$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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.