Federal Posted August 9, 2006 Share Posted August 9, 2006 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 https://forums.phpfreaks.com/topic/17079-picking-a-random-group-of-records-from-a-database/ Share on other sites More sharing options...
AndyB Posted August 10, 2006 Share Posted August 10, 2006 [code]$query = "SELECT * from your_tablename ORDER by RAND() LIMIT 40";[/code] Link to comment https://forums.phpfreaks.com/topic/17079-picking-a-random-group-of-records-from-a-database/#findComment-72139 Share on other sites More sharing options...
corbin Posted August 10, 2006 Share Posted August 10, 2006 [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 https://forums.phpfreaks.com/topic/17079-picking-a-random-group-of-records-from-a-database/#findComment-72147 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.