Creating a Voting Poll With PHP And MySQL Part 2/2 - Capturing votes for the poll
(Page 2 of 4 )
The poll.php file (which is included with the support material at the end of this article) actually displays our poll and lets visitors chose an answer and see the voting tallies.
Poll.php is divided into three functions:
- ShowPoll: Shows the poll and allows the user to vote
- AddVote: Actually adds the users vote to the pollAnswers table
- ShowVotes: Displays the tallied votes in a typical poll format
Let's talk about each of these three functions now. The ShowPoll function actually displays the poll with selectable radio buttons in the browser. Once a user has chosen their desired poll answer, they click on a button that submits their vote and calls the AddVote method. The ShowPoll function automatically displays the most recently added poll for the user to vote on using a select query, like this:
$strQuery = "SELECT * FROM pollQuestions ";
$strQuery .= "ORDER BY pk_Id DESC LIMIT 1";
$pResult = mysql_query($strQuery);The ShowPoll function generates a form, which allows us to retrieve the users choice for the poll when it is displayed:
<form name="frmVote" action="poll.php?pollId=<?php echo $pRow["pk_Id"]; ?>" method="post">The "action" attribute of the poll passes a "pollId" get variable back to our script, which tells it to call the AddVote method. The poll is displayed as a HTML table with the devArticles logo, which is thrown in for some good measure:

Each option for the poll is displayed within a <td> tag by using a for loop, like this:
<tr>
<td bgcolor="#FFEFCE" style="padding-left:10">
<?php
for($i = 1; $i <= 5; $i++)
{
if($pRow["answer" . $i ] != "")
{
?>
<input type="radio" name="answer" value="<?php echo $pRow["answer$i"]; ?>">
<?php echo $pRow["answer" . $i]; ?>
<br>
<?php
}
}
?>
<br>
<input type="submit" value="Vote Now">
<br>
</td>
</tr>When the "Vote Now" button is clicked, our poll.php script automatically calls the AddVote function. The AddVote function starts of by getting access to the $pollId, $answer and $recentPollId variables:
global $pollId;
global $answer;
global $recentPollId;$pollId is the ID of the poll that the vote is being added for. $answer is the actual value of the answer that the user has chosen, so for the poll shown above, if I chose soccer as my answer, then $answer would be "soccer". Lastly, the $recentPollId value is the ID of the most recent poll added to the database. This is retrieved at the top of the script using the following code:
$strQuery = "SELECT pk_Id FROM pollQuestions ORDER BY pk_Id DESC LIMIT 1";
$pResult = mysql_query($strQuery);
if($pRow = mysql_fetch_row($pResult))
{
$recentPollId = $pRow[0];
}
else
{
die("No poll exists at this point in time.");
}As you'll recall, our pollAnswers table has a field named "visitorIP", which allows us to store the IP address of the user voting. We retrieve the users IP like this:
$visitorIP = $HTTP_SERVER_VARS["REMOTE_HOST"];As is the trend, our poll.php script uses a cookie to keep track of which polls a user has voted for (we will discuss this soon). If the user is trying to vote again, then we redirect him/her to the ShowVotes function instead:
// Did the user choose an option?
if($answer == "")
{
ShowPoll();
}
// Has the user already voted?
if(isset($HTTP_COOKIE_VARS["has_voted_$recentPollId"]))
{
ShowVotes();
return;
}Our script checks for a value stored within the $HTTP_COOKIE_VARS array, which contains a list of all of the cookies set on our site for the current user. When a vote is added to the pollAnswers table, a cookie is set on the voters machine in the form of has_voted_[pollId], where [pollId] is the numerical Id of the poll. If this value exists for the current poll, then it means that the user has already voted, and we redirect him/her to the ShowVotes function, which displays the tallied votes.
Next, we execute an insert query against the pollAnswers table to add the users vote to the database:
$strQuery = "INSERT INTO pollAnswers VALUES(";
$strQuery .= "0, $pollId, '$answer', '$visitorIP')";
if(mysql_query($strQuery))
{
...If the query succeeds, then we set a cookie for this poll, indicating that the user has already voted for it:
setcookie("has_voted_" . $pollId, 1, time() + 3600 * 24 * 30);If our poll has an id of 1, then we have just created a new cookie named "has_voted_1" with the value of 1. The cookie is set to expire in 30 days (this value is specified in seconds: there are 3600 seconds in an hour, 24 hours in a day, and approx. 30 days in a year). The complete function definition for the setcookie function looks like this:
int setcookie (string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])
When you use the setcookie function to set a cookie, PHP adds information to the header for the script before it is sent to the browser. Because of this, you should either use the setcookie function before outputting anything to the browser, or use output buffering with the ob_start and ob_end_flush functions.
Once we've added the users vote to the pollAnswers table and also set a cookie indicating that he/she can't vote for this same poll again, we call the ShowVotes method, which displays the tallied poll results.
Next: Displaying the tallied results >>
More MySQL Articles
More By Mitchell Harper