How to create a raffle program

In this tutorial I’m going to show you how to create a raffle program which will randomly select records from a mysql database.

 

Requirements

  • jQuery
  • Wampserver

 

Initial Script

First, create a new file and call it raffle.php. This is where we will put the codes for randomly selecting records using javascript.
Declare an array which will temporarily store the names of the participants and winners. Then initialize the winner_index to 0. If you have already spent some time in programming, you know that winner_index is a way to keep track how many winners were already selected on the current session. This is also a way of making sure that we store each of the winners on a different index in the array.

var participants = [];
var winners = [];
var winner_index = 0;

Once the document has been fully loaded, we initialize the total number of names to be displayed to 30. Then we create an event handler once btn_random is clicked by the user. We haven’t created the btn_random yet since where still on the script so hold your horses and keep reading.
Clicking the btn_random button will cause a post request to the server and this is through the $.post() function in jQuery. It’s a convenience function primarily used to post or load data from the server. In this case, were loading the data from loader.php a script which we will create later. But what it does is select random records from the database and then returns a JSON string which is then used by our raffle program. As you can see in the code, we used $.parseJSON() function before assigning the data to the array of participants. This is used to convert the JSON String into a Javascript Object. This is to prevent the data from being treated as a string. Finally, we execute the RunRaffle() function which takes up 2 arguments: the total number of names to raffle and then the array of names to raffle.

$(function(){
	var total_count = 30;	
	$('#btn_random').click(function(){
		$.post('loader.php', function(data){
		participants = $.parseJSON(data);
			
		RunRaffle(total_count, participants);
	                 });
	});				
});

 

Loading the data

I guess its only proper to first show you how to load the names that were going to raffle from the database before I go through the meat of the program.

Create a new file and name it loader.php. Include your database configuration. Then set the character set to UTF8, this makes sure that we don’t get any errors when dealing with names which are made up of characters which are not very friendly when you retrieve them from the database.
Nex, we select the records randomly from the database and that is by using the RAND() function in mysql. If you’re interested with the technicalities just visit the link. But basically the RAND() function is used to randomize the results which are being returned from a query but its only effective if there are a hundred records or more. Its almost always certain that this function will select the same records over and over again but only in a different order. If say you only have 30-100 records. And note that RAND() function is actually a very expensive operation when it comes to performance so don’t use it on production. But its perfectly fine if you use it on just raffle programs or similar operations.

<?php

require_once('seminar_config.php'); $db->query("SET CHARACTER SET utf8"); $select_random = $db->get_results("SELECT participant FROM tbl_participants

WHERE state = 1 OR state = 4 ORDER BY RAND() LIMIT 30");

 

?>

We then loop through the records and assign it to an array. As you can see we don’t actually need to assign an index to the current record since php does this automatically for us, that’s just sweet! After were done looping through all the records we just use the json_encode() function to convert the $data array into its JSON String representation. There’s also a note from the php.net site that this function only works for UTF8 encoded data so setting the character set to UTF8 in mysql is  actually really useful. Yes you can try not setting the character set to UTF8 and the function will still work, but not for all characters. If json_encode() doesn’t understand it, it will probably be set to null and you’ll get some null values on your JSON string.

if(!empty($select_random)){
	foreach($select_random as $k=>$v){
		if($v->participant != null){
			$data[] = $v->participant;
		}
	}
	echo json_encode($data);
}

 

Meat

After loading up the data that we need its now time to do the code for the presentation of the raffle. The visual signal that will let the audience know that this is actually a raffle program. Because you can’t just pull out random names from the database without any visual impact. And were using jQuery for that purpose, all we have to do is to present a specified number of names. In this case we want 30 names to show up on the interface, then we just change the background color of its container in a successive fashion. There are 3 elements which makes this program tick:

  • Math.random() – although we already randomize what were selecting from the database, we also do this on the client side for presentation purposes.
  • .next() – jQuery’s .next() function which is basically used to determine the next element after the current element that is being selected.
  • setTimeout() – a Javascript function which is used for delaying the execution of another function. In the raffle program it is used to achieve the effect of slowly decreasing the speed in which the light is looping through the names while time passes by.

Declare the RunRaffle() function:

function RunRaffle(intCount, people){
   //magic happens here
}

Inside it we first initialize where we are going to append the list of names. In this case were appending it into an element which has the id of raffle. This element is an ordered list. After that, we just empty the current contents of the ordered list. This is to make sure that we don’t populate the whole interface with a bunch of names from the database.  Don’t worry we’ll also be writing all the html later.

var jRaffle = $("#raffle");
jRaffle.empty(); //this clears all the contents of the ordered list

Next, we just fill the ordered list with the names that we have fetched earlier from the database. But before we actually append it into the list we first check whether its null and that its not an existing winner. This is some sort of an assurance that we don’t put the names of the winners on the list of names to raffle in case the query failed us.

for (var intI = 0 ; intI <= intCount ; intI++){
			
if(people[intI] != null && check_existing(winners, people[intI]) == false){
	jRaffle.append("<li><div class='grey'>" + people[intI] + "</div></li>");
}
}

Next, we change the background color of the first name in our list.  Then Initialize the pause time, the pause time is the amount of time that we are going to run the program. Finally, the intDelay is the amount of time used to jump from one name to another.

var jCurrentLI = jRaffle.find("li:first").addClass("on");  //find the first name that was appended on our list
var intPause = 40; //set initial value of pause time
var intDelay = (4500 + (Math.random() * 2000)); //get time to wait before chaining pause time

Next, create an anonymous function and assign it to a variable called Ticker.

var Ticker = function(){

}

Inside it we define the next name to be selected, if we don’t have anything else on the list we go back to the first name on our list.

var jNextLI = jCurrentLI.next("li"); //next name to highlight
if (!jNextLI.length){ //check whether jNextLI has something in it     jNextLI = jRaffle.find("li:first"); //go back to the first name
}

Then we remove the highlight from the current name and add the highlight to the next name.

jCurrentLI.removeClass("on"); //remove highlight from current
jjNextLI.addClass("on"); //add highlight to next

Then check  whether to make the chaining slower. Remember that the higher the number of the variable intPause, the slower the movement from the current name to the next name will execute. This means that the intPause variable effectively determines the next winner after we reach a certain value.

jCurrentLI = jNextLI; //for the next iteration
if (intDelay > 0){
	intDelay -= intPause; //intDelay = intDelay – intPause
} else {
	intPause *= (1 + (Math.random() * .1)); //intPause = intPause * random value
}

Finally, when the intPause variable reaches a value of 400 or above we stop the current session of iterations. What we do here is to append the current winner to the list of winners and that is if the current name isn’t already stored in the array of winners, for this we used the check_existing() function which we will create later. We also submitted the name of the current winner to winners.php which basically just saves the name of the current winner into our database and changes its state so that it won’t be selected again. If for some reason a name is selected twice, we just clear out the container which stores the name of the current winner and we don’t add anything to the list.

if (intPause >= 400){
	iif(check_existing(winners, jCurrentLI.text()) == false){
		$('#winners').append('<li>' + jCurrentLI.text() + '</li>'); //append current winner to list of winners
		winners[winner_index] = $.trim(jCurrentLI.text()); //housekeeping  $.post('winners.php', {'winner' : $.trim(jCurrentLI.text())}); //save winner to database
		$('#divider').html(jCurrentLI.text()); //current winner
		
		winner_index++; //add 1 to the index
					
	}else{
		$('#divider').html(''); //clear the container for current winner
	}
				
} else { //while intPause is not >=400 increase delay for Ticker
	setTimeout(Ticker, intPause); //set delay for the ticker to be called
}

Then we just call the anonymous function through the variable Ticker. Note that were calling it just like a normal function.

Ticker();

 

Check Existing

For the check_existing() function it returns true if it found the name of the current winner in the array and false if it didn’t find it. It takes up two arguments, the winners array and the selected name.

function check_existing(arr,obj){
	 return (arr.indexOf(obj) != -1);
}

 

Commit Selection

The last thing that we have to do is to commit the selected winners to our database. Just change the state of whoever gets selected into something that’s not specified on the select statement.

$winner = mysql_real_escape_string($_POST['winner']); 

$db->query("UPDATE tbl_participants SET state=4 WHERE participant='$winner'");
$db->query("INSERT INTO tbl_winners SET winner='$winner'");

Yup I know what I said above might be confusing so here’s an explanation. For example on your query for selecting records you only select those whose state is 1:

SELECT * FROM tbl_participants WHERE state=1 ORDER BY RAND();

All you have to do in your update is to set a different state:

UPDATE tbl_participants SET state=4 WHERE participant=’something’

Then finally insert the name of the winner into another table. That is if you want to keep track of those who are selected. But you can probably just select all records with the state of 4 if you don’t want to do this extra step.

 

Markup

I explicitly delayed the html for the last part since this is the most boring part.

<div id="header">
	<img src="images/raffle_header.png" />
</div>
<div id="container">
<input type="button" id="btn_random" value="Select"> <!-execution->
<ol id="raffle"> <!-for viewing the names to iterate from–>
	
</ol>
</div>

<div id="bottom">
<div id="current">

	<p>Current:</p>
		<div id="divider"> <!—for viewing the current ->
		
		</div>

</div>
<div id="list">

<p>Winners:</p>
	<div id="winners"> <!—for viewing the list of winners->

	</div>
</div>
</div>

 

Sources

http://www.bennadel.com/resources/presentations/jquery/raffle.htm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s