如何使用一定数量的随机奖品构建“点击赢”类型的比赛

I realize this might be a confusing question so I will try and explain further.

I have been tasked with creating a Facebook competition tab on our page for users to click on a box and to be given a random prize.

There is going to be a finite number of each prize and one major prize.

I am just thinking of the best way to structure and implement this.

All I can think of is a database table to store the prizes with id, name, value and number_available.

Then, when the user clicks the box, a random number is generated between the min and max id's of the table, look up the db row with that id and check if there are any available, if there are, print out the details for the prize. If there's not any of that prize available then keep going until we get a prize that's still in 'stock'.

I think that's not a bad way to do it but not efficient when it comes down to relying on there being some of a particular prize left. If for example there were only one or two prizes left it could take a while for the right random number to be generated for prizes that are left.

The other thing that is bothering me is the major prize. Should I leave it to chance and just let it be won fair and square as soon as that random number is generated or should there be some kind of weighting applied to it to stop it being won quickly (competition is going to run until the end of the month)?

Then, if yes, how should I apply some kind of weighting?

Surely you don't need to keep repeating the query?

Your query would be something like:

SELECT * FROM `prizes` WHERE `number_available`>0 ORDER BY RAND() LIMIT 1

Then after it pulls that prize out it'd update the table to set number_available to number_available-1:

UPDATE `prizes` SET `number_available`=`number_available`-1 WHERE `id`='ID'

In which case it wouldn't need to repeat? Once the number_available is 0 then it's not part of the query anymore.

If you implement it like you proposed, you have to be careful about running into an endless loop, as soon as there are no prices available.

You could do it like this:

<?php

$prices = array();
$result = mysql_query("SELECT * FROM prices WHERE stock > 0");
while($row = mysql_fetch_assoc($result))
{
    $prices[] = array();
}  
shuffle($prices);
$price = array_pop($prices);
mysql_query("UPDATE prices SET stock = stock - 1 WHERE id = " . $price['id'] . ";");
echo "Congratulations, you have won " . $price['name'];

?>

As for the weighting of the major price: That's really your or your company's choice, can't help you there...

if you would like to read on this