Basic Poll Script in PHP

Basic Poll Script in PHPThis article will teach you how to write a basic poll script in php. You will mysql and a new version of PHP.

The first step is to create a database that will hold the informationall the polls we want. For this article we will be creating a poll thatwill have 3 options. Yes, No, and Not Sure. So we will want to createfeilds for each of those. I used Option1, Option2, and Option. We willalso need a title and a question to ask. I created those as varchars.Another feild will hold the total number of votes total. The mostimportant colum is the ID colum which will be an auto increment tinyintthat will help use to select, edit, and add new records. Here is theschema of my table:

# Table structure for table `poll_data`#CREATE TABLE poll_data ( ID tinyint(4) NOT NULL auto_increment, Option1 tinyint(4) NOT NULL default '0', Option2 tinyint(4) NOT NULL default '0', Option3 tinyint(4) NOT NULL default '0', Votes tinyint(4) NOT NULL default '0', Title varchar(25) NOT NULL default '', Question varchar(50) NOT NULL default '', PRIMARY KEY (ID)) TYPE=MyISAM;

Now that we have the table set up, we want to get coding. Most ofthe time, when you are going to write a script or program you will wantto break it down into small parts. Like:
  1. Display the Title and Question of the Poll.
  2. Show the captions of each vote option, the percent of the total votes, and the total votes for each.
  3. Create a file that will allow the user to vote in the poll.
Those are the main functions of our script. Now that we those setup, we want to break each of those down into smaller objectives.
  1. Display the Title and Question of the Poll
    a. Connect to the database
    b. Select the Newest record from the database
  2. Show Captions of each vote.
    a. Select the votes for each option, and select the total votes in the poll.
    b. Take the number of votes and divide by the total number of votes to find the percent.
  3. Create a file that will allow the user to vote in the poll
    a. Update the row where the user voted.
We will want to set up some variables to help us connect to the database. Like This:

$dbhost = "localhost";
$dbname = "YourDataBase";
$dbuser = "YourUserName";
$dbpass = "YourPass";

Then, we will connec to the database.

$link_id = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

Now we have some queries to do. One to select the current Title andQuesiton of the Poll, and the other to get all the information on thevotes and total votes. There is a problem though. We need to getinformation about the current or newest poll. This is where are IDcolum comes into play. We can select the Title and Question in Descending Orderso that the newest record will be at the top. See, every time a new rowis inserted, the ID colum has 1 added to it, or it is Auto Incremented.So, the newest row will have the largest ID, so we can sort that formLargest to Smallest to get the newest record. Also, we only want onerow to be returned so we tack on Limit 1 at the end. Then we want toturn that result into an array for easy access.

$sql = "SELECT `Title`,`Question`,`ID` FROM `poll_data` ORDER BY `ID` DESC LIMIT 1";if(!($result = mysql_query($sql))) die(mysql_error());$PollData = mysql_fetch_array($result)

Now that we have the Title and Question of the poll, we want theall the good stuff, the votes and the percentages. Again we want thenewest record, so we use desc order again.

$sql = "SELECT `Option1`,`Option2`,`Option3`,`Votes` FROM`poll_data` WHERE `ID` = '" . $PollData['ID'] . "' ORDER BY `ID` DESCLIMIT 1";
if(!($result = mysql_query($sql))) die(mysql_error());
if(!($VoteData = mysql_fetch_array($result))) die(mysql_error());

Now for some math. We need to find out the percentages that each choicehas. Once we find that percent, we can make an image and set it to havea width of that percentage. The image will give us the bars, that weall love. To find the percent we need to get the votes that a choicehas then divide it by the total votes in the poll, then multiply it by100, then round that number to get a 2 digit number. After all the mathis done, we add a % sign to the end of it. What is there are no votesfor a certain option? We will get an unsightly error saying divison by0. So we Check to see if the votes are 0 and if they are, set thepercent to 0%.

if($VoteData["Option1"] != 0) {
$VotePercent1 = Round(($VoteData["Option1"] / $VoteData["Votes"]) * 100) . "%";
} else {
$VotePercent1 = 0 ."%";
}
if($VoteData["Option2"] != 0) {
$VotePercent2 = Round(($VoteData["Option2"] / $VoteData["Votes"]) * 100) . "%";
} else {
$VotePercent2 = 0 ."%";
}
if($VoteData["Option3"] != 0) {
$VotePercent3 = Round(($VoteData["Option3"] / $VoteData["Votes"]) * 100) . "%";
} else {
$VotePercent3 = 0 ."%";
}

Now that we have all the data we need, we need to display thatinformation in the table. Before you do this, you need to make an imagethat is 20 pixels high and 1 pixel wide of any color. This part is veryself explainatory. We have a table and output the data. We set theimage width to be the vote percent. We have a form with radio buttonsto let the user pic their vote.

<html>

<head>>
<title>Basic Poll - Written by Adman</title>
</head>
<body>
<form method="POST" action="vote.php">
<table width="500" border="1" cellspacing="0" cellpadding="8">
<tr>

<td colspan="3"><b><?=$PollData['Title']?> - <?=$PollData['Question']?></b></td>
</tr>
<tr>
<td width="35%">

<input type="radio" name="Vote" value="Option1">
Yes</td>
<td width=60%>
<img src="bar.gif" width="<?=$VotePercent1?>" height="20">
</td>

<td><?=$VoteData["Option1"]?> Votes</td>
</tr>
<tr>
<td width="35%">
<input type="radio" name="Vote" value="Option2">

No </td>
<td width=60%>
<img src="bar.gif" width="<?=$VotePercent2?>" height="20">
</td>
<td><?=$VoteData["Option2"]?> Votes</td>

</tr>
<tr>
<td width="35%">
<input type="radio" name="Vote" value="Option3" >
Not Sure</td>
<td width="60%">

<img src="bar.gif" width="<?=$VotePercent3?>" height="20">
</td>
<td><?=$VoteData["Option3"]?> Votes</td>
</tr>

<tr>
<td colspan="3">
<center>
<input type="submit" name="Submit" value="Vote">
</center>
</td>

</tr>
</table>
</form>
</body>
</html>

Now that we have the display done. We are ready to write thescript that lets the user vote in the poll. On to the next page!First we check to see the user actually did vote, if not, exit thescript. Since the variable was passed through a post form, we have touse $_POST.

if(empty($_POST["Vote"]))  die("You did not enter your vote");

If the script is still running, we need to connect to thedatabase like we did before, and select the current data on the poll.We want to select all the vote data form the newest record. Then turnit into an array.

$dbhost = "localhost";
$dbname = "misc";
$dbuser = "root";
$dbpass = "trigger";

$link_id = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname);

$sql = "SELECT `Option1`,`Option2`,`Option3`,`Votes`,`ID` FROM `poll_data` ORDER BY `ID` DESC LIMIT 1";
if(!($result = mysql_query($sql))) die(mysql_error());
if(!($PollData = mysql_fetch_array($result))) die(mysql_error());

Now that we have a database connection, we need to decided whichoption to update. We need to add 1 to the current number of votes, andadd 1 to the total number of votes. After that has been done, we needto update that row in the database. So we use the update clause to setthe new records. Just like before we need to user $_POST becuase thevariables we transmitted through a post metod form.

if($_POST["Vote"] == "Option1") {
$Votes1 = $PollData["Option1"] + 1;
$TotalVotes = $PollData["Votes"]+ 1;

$sql = "UPDATE `poll_data` SET `Option1`='$Votes1', `Votes`='$TotalVotes' WHERE `ID` = '". $PollData['ID'] . "' LIMIT 1";
if(!($result = mysql_query($sql))) die(mysql_error());
echo "Vote successful! <a href="index.php">Back</a> to the poll.";
}
else if ($_POST["Vote"] == "Option2"){
$Votes2 = $PollData["Option2"] + 1;
$TotalVotes = $PollData["Votes"]+ 1;

$sql = "UPDATE `poll_data` SET `Option2`='$Votes2', `Votes`='$TotalVotes' WHERE `ID` = '". $PollData['ID'] . "' LIMIT 1";
if(!($result = mysql_query($sql))) die(mysql_error());
echo "Vote successful! <a href="index.php">Back</a> to the poll.";
}
else {
$Votes3 = $PollData["Option3"] + 1;
$TotalVotes = $PollData["Votes"] + 1;

$sql = $sql = "UPDATE `poll_data` SET `Option3`='$Votes3',`Votes`= '$TotalVotes' WHERE `ID` = '". $PollData['ID'] . "' LIMIT 1";
if(!($result = mysql_query($sql))) die(mysql_error());
echo "Vote successful! <a href="index.php">Back</a> to the poll.";
}

voilla!! Your done. All you have to do is save the file. Those are thebasics of a poll. In my next article, I will tell you how to administeryour poll. If you have any problems, talk to me on TutorialForums, myemail is z-team@attbi.com. Feel free to email me to talk me, I will beglad to help you.

Related Articles

  • Where to Get Some Scripts
    You may find the list of basic scripts here.
  • Beginner JS Pt. 1
    This tutorial is a well laid out recipe for basic Javascript. The article is brief and is limited to three topics: Calling the Script, Writing Comments, and Doing Stuff (Basic). Illustrations make it easy.
  • Script Execution Time
    Learn how to add a time execution script to your pages.
  • The Basics- JavaScript Tutorial
    To get started with JavaScript, you will want to be able to see the tag that will set a script apart from the HTML. The tags used to begin and end a script are the tags. The opening tag should appear like this
  • Rate it! Poll
    This is an awesome tutorial that will show you step by step how to create a way to take a poll on your site. People for the most part enjoy participating in polls so this could also help you bring extra traffic to your site.
  • Beginner JS Pt. 2
    This tutorial is a well laid out recipe for basic Javascript. The article is brief and is limited to three topics: Calling the Script, Writing Comments, and Doing Stuff (Basic). Illustrations make it easy.
  • Creating Alerts
    A simple guide to using alerts (and annoying your visitors)
  • Using PHP 'if' Statements
    Using if statements, you can check to see if a variable equals something else, and then execute a line of code if it is, and execute another line of code if it isnt. This tutorial is meant for beginners.
  • Customizing the Status Bar Message
    Place this script in the section of your web page code to add a scrolling marquee to your status bar.
  • Stop Right Mouse Clicks
    Stop people from getting at your source by right clicking on your web page. Sounds good, but doesnt protect you totally, you can never fully protect your work, but it will make it harder.

Contact Web Design Outsource and get started today

Need Website Designing, Development, Redesigning, Maintenance and SEO services or help growing your company's web presence? Request a free Quote Now.