View Full Version : select random number from a table
04-12-2012, 12:29 AM
im going to start writing a script tomorrow that once every week will pick a number at random from a table of tickets, its a lot like a lottery game, however im asking now as i dont know how is the best way to work out how many tickets are in the table 'lottery_tickets' and then do a random number: mt_rand(1,x); to come up with the random number but within the ammount that is in the table.
thanks guys :)
04-12-2012, 12:44 AM
Put the numbers into an array and shuffle the array.
When you pick the first array item, it will be random (from the shuffled array).
Have another column in your table that identified the ticket (id) and has a pick column.
You can mark that one so it never gets picked again.
04-12-2012, 12:56 AM
Thanks for the reply, how would I go about shuffling the array? Could you provide a breif example please if its no trouble
04-12-2012, 01:24 AM
You would be doing a MySQL query, but I don't have any availability to your database, tables, or columns ...
Save this script as "test.php" and run it over and over again.
$tickets = array("1234","6546","67657","3422","2346");
echo "The first ticket in the original array is: ".$tickets."<br><br>";
// now we shuffle the array.
echo "The first random ticket is: ".$tickets."<br><br>";
// notice in both cases, we're looking at the first array item.
04-12-2012, 11:39 AM
i have two tables, one for the tickets:
ticketid being the auto inc
and the actual lottery table which has the date it will be drawn, ect
but i didnt want to use mysql number rows to figure out how many tickets there are because people say its slow, and there could be more than say 10,000 tickets, so would it be worth more to use COUNT(ticketid) also, after it is drawn it will be emptying the table, will this reset the auto inc to start at 1 again, or will i have to go in manually to change it back again?
04-14-2012, 04:36 PM
also, how would i go about triggering a script to run, without a cron job, every wednesday and saturday at 5 pm?
04-14-2012, 06:25 PM
What will happen if you don't do anything to the data until someone
views the site after 5pm on Wed and Sat? If you don't trigger the script
to run automatically, what consequences would there be?
If it's after 5pm on Wed and a person views the site, or access the script,
your script will execute. So you don't need to run it automatically?
It's sort of like "If a tree falls in the forest and nobody is there... "
04-14-2012, 06:56 PM
i get what you mean, i think i will use a cron job for it :) thanks alot :)
also, if i do empty the table will it reset my auto inc back to 0/1 or will i have to do that myself each time?
04-14-2012, 08:01 PM
See this ... two methods:
DELETE FROM retains the auto-increment seed.
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.